一般的Bean對象都是被定義在*.xml中的,xml中的各個bean的屬性注入非常方便。
但是有些時候在閱讀xml的時候就非常的費勁兒,尤其是在文件中定義了很多內容。
有的定義好了,基本不會改變,有的就需要改變。這個時候可以使用BeanFactoryPostProcessor接口來解決。
*.beans.factory.config.BeanFactoryPostProcessor;這個名稱的意思說當依賴注入到BeanFactory之後可以進行處理,具體怎麼處理看情況而定。
*.beans.factory.config.PropertyPlaceholderConfigurer實現了BeanFactoryPostProcessor接口。
就可以用它來完成。
<?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="configBean" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>hello.properties</value>//資源文件名稱
</property>
</bean>
<bean id="helloBean" class="com.baidu.HelloBean">
<property name="helloWord">
<value>${helloWord}</value>//資源文件屬性名
</property>
....
</bean>
......
</beans>
PropertyPlaceholderConfigurer類會讀取hello.properties文件到本地location,並將讀取到的資源文件屬性值賦值給helloWord。從而完成依賴注入
另一種情況是完成高權限的統一。spring提供了一個BeanFactoryPostProcessor實現類。
*.beans.factory.config.PropertyOverrideConfigurer;
<?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="configBean" class="org.springframework.beans.factory.config.PropertyOverrideConfigurer">
<property name="location">
<value>hello.properties</value>
</property>
</bean>
<bean id="helloBean" class="com.baidu.HelloBean">
<property name="helloWord">
<value>Hello!caterpillar!</value>
</property>
....
</bean>
....
</beans>
helloBean.helloWord=Hello!Justin!