Spring的框架中爲您提供了一個 BeanFactoryPostProcessor 的實作類別: org.springframework.beans.factory.config.PropertyPlaceholderConfigurer。藉由這個類別,您可以將一些組態設定,移出至.properties檔案中,如此的安排可以讓XML定義檔負責系統相關設定,而.properties檔可以作爲客戶根據需求,自定義一些相關的參數。
來看一個Bean定義檔的實際例子:
- beans-config.xml
<?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="onlyfun.caterpillar.HelloBean"> <property name="helloWord"> <value>${onlyfun.caterpillar.helloWord}</value> </property> </bean> </beans>
假設在helloBean中有許多依賴注入的屬性,這些都是比較不常變動的屬性,而其中helloWord會經常變動,可以透過hello.properties來簡單的設定,而這個資訊已設定在configBean的location屬性中:
- hello.properties
onlyfun.caterpillar.helloWord=Welcome!
在helloBean的helloWord屬性中,${onlyfun.caterpillar.helloWord}將會被hello.properties的helloWord所取代。
如果有多個.properties檔案,則可以透過locations屬性來設定,例如:
- beans-config.xml
<?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="locations"> <list>
<value>hello.properties</value> <value>welcome.properties</value> <value>other.properties</value>
</list> </property>
</bean> <bean id="helloBean" class="onlyfun.caterpillar.HelloBean"> <property name="helloWord"> <value>${onlyfun.caterpillar.helloWord}</value> </property> ... </bean> </beans>