Spring的PropertyPlaceholderConfigurer應用


Spring 利用PropertyPlaceholderConfigurer占位符

 

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>conf/sqlmap/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/mail.properties</value>  

    <value>classpath: conf/sqlmap/jdbc.properties</value>//注意這兩種value值的寫法

   </list>

  </property>

</bean>

3.譬如,jdbc.properties的內容為:

jdbc.driverClassName=com.mysql.jdbc.Driver

jdbc.url=jdbc:mysql://localhost/mysqldb?useUnicode=true&amp;characterEncoding=UTF-8&amp;zeroDateTimeBehavior=round;

jdbc.username=root

jdbc.password=123456

4.那么在spring配置文件中,我們就可以這樣寫:

<bean id="propertyConfigurer"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

  <property name="locations">

   <list>

    <value>classpath: conf/sqlmap/jdbc.properties </value>

   </list>

  </property>

</bean>

<bean id="dataSource"class="org.apache.commons.dbcp.BasicDataSource"destroy-method="close">

  <property name="driverClassName"value="${jdbc.driverClassName}" />

  <property name="url" value="${jdbc.url}" />

  <property name="username" value="${jdbc.username}"/>

  <property name="password"value="${jdbc.password}" />

</bean>

5.這樣,一個簡單的數據源就設置完畢了。可以看出:PropertyPlaceholderConfigurer起的作用就是將占位符指向的數據庫配置信息放在bean中定義的工具。

6.查看源代碼,可以發現,locations屬性定義在PropertyPlaceholderConfigurer的祖父類PropertiesLoaderSupport中,而location只有 setter方法。類似於這樣的配置,在spring的源程序中很常見的。

PropertyPlaceholderConfigurer如果在指定的Properties文件中找不到你想使用的屬性,它還會在Java的System類屬性中查找。

我們可以通過System.setProperty(key, value)或者java中通過-Dnamevalue來給Spring配置文件傳遞參數。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM