Spring技巧之简洁配置

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等都能识别,不需要我们动手一点一点的录入配置文件,大多数工具对新的配置方式还不能识别,因此,请根据实际情况酌情使用。

你可能感兴趣的:(Spring技巧之简洁配置)