1、PropertyPlaceholderConfigurer是一個bean工廠后置處理器的實現,也就是BeanFactoryPostProcessor接口的一個實現。PropertyPlaceholderConfigurer可以將上下文(配置文件)中的屬性值放在另一個單獨的標准java Properties文件中去。在XML文件中用${key}替換指定的properties文件中的值。這樣的話,只需要對properties文件進行修改,而不用對xml配置文件進行修改。
2、在Spring中,使用PropertyPlaceholderConfigurer可以在XML配置文件中加入外部屬性文件,當然也可以指定外部文件的編碼,如:
<bean id="propertyConfigurer"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location"> <value>resource/jdbc.properties</value> </property> <property name="fileEncoding"> <value>UTF-8</value> </property> </bean>
當然也可以引入多個屬性文件,如:
<bean id="propertyConfigurer"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>/WEB-INF/AppConfig.xml</value> <value>classpath: resource/jdbc.properties</value>//注意這兩種value值的寫法 </list> </property> </bean>
3、譬如,jdbc.properties的內容為:
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/myspring?useUnicode=true&characterEncoding=UTF-8 jdbc.username=root jdbc.password=123456
4、那么在Spring配置文件中,我們就可以這樣寫:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <value>classpath:jdbc.properties</value> </property> </bean> <bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <property name="removeAbandoned" value="true" /> <property name="removeAbandonedTimeout" value="20"/> <property name="logAbandoned" value="true"/> </bean>
5、這樣,一個簡單的數據源就設置完畢了。可以看出:PropertyPlaceholderConfigurer起的作用就是將占位符指向的數據庫配置信息放在bean中定義的工具。
6、查看源代碼,可以發現,locations屬性定義在PropertyPlaceholderConfigurer的祖父類PropertiesLoaderSupport中,而location只有setter方法。類似於這樣的配置,在spring的源程序中很常見的。
PropertyPlaceholderConfigurer如果在指定的Properties文件中找不到你想使用的屬性,它還會在Java的System類屬性中查找。
我們可以通過System.setProperty(key, value)或者java中通過-Dnamevalue來給Spring配置文件傳遞參數。
7、我們還可以使用注解的方式實現,如:<context:property-placeholder location="classpath:jdbc.properties" />,效果跟PropertyPlaceholderConfigurer是一樣的。
---------------------------------------------------------------------------------
Blog:http://www.cnblogs.com/linjiqin/
Hadoop交流群(250363249)、Java+Oracle交流群(158560018)
題外話:
本人來自鐵觀音的發源地——泉州安溪,有需要正宗安溪鐵觀音的友友歡迎Q我:416501600。