Spring中PropertyPlaceholderConfigurer的使用

cyzero發表於2012-12-24

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配置檔案傳遞引數。

相關文章