Spring2.0在配置上調(diào)整了不少地方,增加更加靈活、簡(jiǎn)潔的配置方式,本文通過(guò)兩個(gè)簡(jiǎn)單的示例來(lái)演示。
??????配置Apache的一個(gè)數(shù)據(jù)源連接池,在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>兩個(gè)標(biāo)簽作為其父級(jí)<bean>標(biāo)簽的一個(gè)屬性來(lái)定義,這樣使得配置文件更加簡(jiǎn)潔,如下所示:
<?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中還有一個(gè)非常實(shí)用的解析器,SimplePropertyNamespaceHandle,若配置文件中引用http: //www.springframework.org/schema/p命令空間,則將會(huì)使用 SimplePropertyNamespaceHandle來(lái)處理這個(gè)Bean的定義,可以在Spring2.0中的Bean中以更簡(jiǎn)單的方式配置設(shè)值方法注入,如下所示:
<?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屬性來(lái)引用另外一個(gè)Bean。
????如,Spring2.0以前的一個(gè)DAO配置:
<bean?id="userDao"?class="com.easyjf.bbs.dbo.springjdbc.UserDaoSpringJdbc">
???????<property?name="dataSource"><ref?bean="dataSource"/></property>
???</bean>??
??使用簡(jiǎn)短屬性方式,則改成如下:
<bean?id="userDao"?class="com.easyjf.bbs.dbo.springjdbc.UserDaoSpringJdbc"?p:dataSource-ref="dataSource"?/>
Spring2.0比以前的版本配置更加靈活、簡(jiǎn)潔,如果手工書寫配置,則比較實(shí)用。當(dāng)然,老的配置方式有很多開發(fā)工具如MyEclipse等都能識(shí)別,不需要我們動(dòng)手一點(diǎn)一點(diǎn)的錄入配置文件,大多數(shù)工具對(duì)新的配置方式還不能識(shí)別,因此,請(qǐng)根據(jù)實(shí)際情況酌情使用。