天天看點

Spring中PropertyPlaceholderConfigurer的使用介紹

PropertyPlaceholderConfigurer是個bean工廠後置處理器的實作,也就是 BeanFactoryPostProcessor接口的一個實作。PropertyPlaceholderConfigurer可以将上下文(配置文 件)中的屬性值放在另一個單獨的标準java Properties檔案中去。在XML檔案中用${key}替換指定的properties檔案中的值。這樣的話,隻需要對properties檔案進 行修改,而不用對xml配置檔案進行修改。

基本的使用方法是:

<bean id="propertyConfigurerForAnalysis" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location">
        <value>classpath:/spring/include/dbQuery.properties</value>
    </property>
</bean>      

其中classpath是引用src目錄下的檔案寫法。

當存在多個Properties檔案時,配置就需使用locations了:(2)

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
       <list>
          <value>classpath:/spring/include/jdbc-parms.properties</value>
          <value>classpath:/spring/include/base-config.properties</value>
        </list>
    </property>
</bean>      

接下來我們要使用多個PropertyPlaceholderConfigurer來分散配置,達到整合多工程下的多個分散的Properties 檔案,其配置如下:(3)

<bean id="propertyConfigurerForProject1" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="order" value="1" />
    <property name="ignoreUnresolvablePlaceholders" value="true" />
    <property name="location">
       <value>classpath:/spring/include/dbQuery.properties</value>
    </property>
</bean>      
<bean id="propertyConfigurerForProject2" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="order" value="2" />
    <property name="ignoreUnresolvablePlaceholders" value="true" />
    <property name="locations">
      <list>
        <value>classpath:/spring/include/jdbc-parms.properties</value>
        <value>classpath:/spring/include/base-config.properties</value>
      </list>
    </property>
</bean>      

其中order屬性代表其加載順序,而ignoreUnresolvablePlaceholders為是否忽略不可解析的 Placeholder,如配置了多個PropertyPlaceholderConfigurer,則需設定為true

至此你已經了解到了如何使用PropertyPlaceholderConfigurer,如何使用多個Properties檔案,以及如何配置多個PropertyPlaceholderConfigurer來分解工程中分散的Properties檔案。至于 PropertyPlaceholderConfigurer還有更多的擴充應用.

轉載自:http://outofmemory.cn/code-snippet/3590/Spring-PropertyPlaceholderConfigurer-usage-introduction