开发框架--讨论Spring技巧之简洁配置

 

Spring2.0在配置上调整了不少地方,增加更加灵活、简洁的配置方式,本文通过两个简单的示例来演示。
      配置Apache的一个数据源连接池,在Spring 2.0以前的版本中,我们可以使用类似下面的配置:
< ?xml version="1.0" encoding="UTF-8"?>
< !DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
< beans>
< bean id="dataSource"
  class="org.apache.commons.dbcp.BasicDataSource"
  destroy-method="close">
  < property name="driverClassName">
   < value>org.gjt.mm.mysql.Driver< /value>< /property>
  < property name="url">
   < value>jdbc:mysql://127.0.0.1:3306/easyjf-bbs< /value> < /property>
  < property name="username">< value>root< /value> < /property>
  < property name="password">< value>mypass< /value>< /property>
 < /bean>
< /beans>
      在Spring2.0中,可以把< value>及< ref>两个标签作为其父级< bean>标签的一个属性来定义,这样使得配置文件更加简洁,如下所示:
< ?xml version="1.0" encoding="UTF-8"?>
< !DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
< beans>
< bean id="dataSource"
  class="org.apache.commons.dbcp.BasicDataSource"
  destroy-method="close">
  < property name="driverClassName"
   value="org.gjt.mm.mysql.Driver" />
  < property name="url"
   value="jdbc:mysql://127.0.0.1:3306/easyjf-bbs" />
  < property name="username" value="root" />
  < property name="password" value="mypass" />
 < /bean>
< /beans>

      另外,Spring2.0中还有一个非常实用的解析器,SimplePropertyNamespaceHandle,若配置文件中引用 http://www.springframework.org/schema/p命令空间,则将会使用 SimplePropertyNamespaceHandle来处理这个Bean的定义,可以在Spring2.0中的Bean中以更简单的方式配置设值 方法注入,如下所示:
< ?xml version="1.0" encoding="UTF-8"?>
< beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:p="http://www.springframework.org/schema/p"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

< bean id="dataSource"
  class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
  p:driverClassName="org.gjt.mm.mysql.Driver"
  p:url="jdbc:mysql://127.0.0.1:3306/easyjf-bbs" p:username="root" p:password="mysql" />
< /beans>

在上面的配置中,使用p:url则可以直接注入BasicDataSource的url属性值,可以使用p:url-ref属性来引用另外一个Bean。
    如,Spring2.0以前的一个DAO配置:
< bean id="userDao" class="com.easyjf.bbs.dbo.springjdbc.UserDaoSpringJdbc">
       < property name="dataSource">< ref bean="dataSource"/>< /property>
   < /bean> 
  使用简短属性方式,则改成如下:
< bean id="userDao" class="com.easyjf.bbs.dbo.springjdbc.UserDaoSpringJdbc" p:dataSource-ref="dataSource" />

Spring2.0比以前的版本配置更加灵活、简洁,如果手工书写配置,则比较实用。当然,老的配置方式有很多开发工具如MyEclipse等都能识别,不需要我们动手一点一点的录入配置文件,大多数工具对新的配置方式还不能识别,因此,请根据实际情况酌情使用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值