1. 程式人生 > >spring配置加載多個properties文件

spring配置加載多個properties文件

lac 存在 cnblogs org bsp 讀取 ace val cati

(一)
首先,我們要先在spring配置文件中。定義一個專門讀取properties文件的類.
例:

1 <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
2     <property name="locations">
3     <list>
4         <value>classpath*:jdbc.properties</value>
5         <!--要是有多個配置文件,只需在這裏繼續添加即可 -->
6
</list> 7 </property> 8 </bean>



這裏為什麽用locations(還有一個location)
一般來說,我們的項目裏面配置文件可能存在多個。
就算是只有一個,那將來新添加的話,只需在下面再加一個value標簽即可,

而不必再重新改動太多。

(二) 使用 spring中 context:property-placeholder
例:

<context:property-placeholder location="classpath:data/mybatis.properties" />

但是不能加載多個properties文件,Spring容器采用反射掃描的發現機制,在探測到Spring容器中有一個 org.springframework.beans.factory.config.PropertyPlaceholderConfigurer的 Bean就會停止對剩余PropertyPlaceholderConfigurer的掃描(Spring 3.1已經使用PropertySourcesPlaceholderConfigurer替代 PropertyPlaceholderConfigurer了)。

換句話說,即Spring容器僅允許最多定義一個PropertyPlaceholderConfigurer(或),其余的會被Spring忽略掉(其實Spring如果提供一個警告就好了)。

拿上來的例子來說,如果A和B模塊是單獨運行的,由於Spring容器都只有一個PropertyPlaceholderConfigurer, 因此屬性文件會被正常加載並替換掉。如果A和B兩模塊集成後運行,Spring容器中就有兩個 PropertyPlaceholderConfigurer Bean了,這時就看誰先誰後了, 先的保留,後的忽略!因此,只加載到了一個屬性文件,因而造成無法正確進行屬性替換的問題.

解決方法:

1     <!-- 加載所有配置文件 -->
2     <context:property-placeholder location="classpath*:data/*.properties"/>
3     <!-- 還可以是下面方式,加載多個目錄中的 -->
4     <context:property-placeholder location="classpath:*.properties,classpath:*/*.properties" /> 




spring配置加載多個properties文件