生成如下的屬性文件(/WEB-INF/jdbc.properties):
jdbc.driver=org.postgresql.Driver
jdbc.url=jdbc:postgresql://localhost/test
jdbc.user=postgres
jdbc.password=
我們的Bean配置如下:
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>/WEB-INF/jdbc.properties</value>
</property>
</bean>
OR
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value></value>
</list>
</property>
</bean>
applicationContext.xml中數據源配置:
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>${jdbc.driver}</value>
</property>
<property name="url">
<value>${jdbc.url}</value>
</property>
<property name="username">
<value>${jdbc.user}</value>
</property>
<property name="password">
<value>${jdbc.password}</value>
</property>
</bean>
我們定義了一個PropertyPlaceholderConfigurer類的實例,並將其位置屬性設置爲我們的屬性文件。
該類被實現爲BeanFactoryPostProcessor(Bean工廠後處理器);並將使用定義在文件中的屬性來代替所有的佔位符(${...}value)。
利用這種技術,我們可以從applicationContext.xml中移除所有特定於主機的配置屬性。
通過這種方式,我們可以自由地爲該文件添加新的Bean,而不必擔心特定於主機屬性的同步性。這樣可以簡化生產部署和維護。