1.PropertyPlaceholderConfigurer類
它是把屬性中的定義的變量(var)替代,spring的配置文件中使用${var}的占位符
<beans>
<bean?id="configBean"?class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
??????????
<property?name="location"><value>db.properties</value></property>
</bean>?
<bean?id="dataSource"?class="org.apache.commons.dbcp.BasicDataSource"?destroy-method="close">
????
<property?name="driverClassName"><value>${jdbc.driverClassName}</value></property>
????
<property?name="url"><value>${jdbc.url}</value></property>
????
<property?name="username"><value>${jdbc.username}</value></property>
????
<property?name="password"><value>${jdbc.password}</value></property>
</bean>
</beans>
db.properties文件
jdbc.driverClassName=org.hsqldb.jdbcDriver
jdbc.url=jdbc:hsqldb:hsql://production:9002
jdbc.username=sa
jdbc.password=root
2.PropertyOverrideConfigurer類
跟PropertyPlaceholderConfigurer功能一樣,不過用法不一樣.不用占位符,在屬性文件中
直接定義屬性的值,這樣就允許有默認值
<beans>
<bean?id="configBean"?class="org.springframework.beans.factory.config.PropertyOverrideConfigurer">
???????????
<property?name="location"><value>db.properties</value></property>
</bean>?
<bean?id="dataSource"?class="org.apache.commons.dbcp.BasicDataSource"?destroy-method="close">
????
<property?name="driverClassName"><value>org.hsqldb.jdbcDriver</value></property>
????
<property?name="url"><value>jdbc:hsqldb:hsql://production:9002</value></property>
????
<property?name="username"><value>test</value></property>
????
<property?name="password"><value>123456</value></property>
</bean>
</beans>
db.properties文件
dataSource.username=admin
dataSource.password=9527
在bean實例時,admin,9527將替代test,123456
3其他
1)如果需要引用多個屬性,將configBean屬性改為
<property?name="locations">
<list>
<value>db.properties</value>
<value>db1.properties</value>
</list>
</property>
2)在ApplactionContext中是自動調用BeanFactoryPostProcessor接口的,如果要在BeanFactory中使用,必須手動添加:
XmlBeanFactory?factory?=?new?XmlBeanFactory(new?FileSystemResource("beans.xml"));
PropertyPlaceholderConfigurer?cfg?
=?new?PropertyPlaceholderConfigurer();
cfg.setLocation(
new?FileSystemResource("jdbc.properties"));
cfg.postProcessBeanFactory(factory);