事情的起因
項目A中依賴了項目B提供的jar包,其中有一部分配置是從jar以xml形式引入的,xml中要求有類似數據庫這樣的profile的環境配置。會產生一個很奇怪的問題,通過最外層的application.properties文件定義的屬性不能被正常解析。
目錄結構:
項目A:
- src/main/resources
|- application.properties
|- my.properties
|- context.xml
- libraries
|- B.jar
|-- my2.properties
|-- context2.xml
代碼:
application.properties
my.name=application
my.properties
my.name=my1
context.xml
<import resource="classpath:context2.xml"/>
<context:property-placeholder ignore-unresolvable="true" order="2" location="classpath:my.properties"/>
<bean id="bean1" class="Bean">
<property name="name" value="${my.name}" />
</bean>
my2.properties
my.name=my2
context2.xml
<bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true"></property>
<property name="location">
<value>classpath:my2.properties</value>
</property>
</bean>
運行后,注入的${my.name}只有兩種情況,my1 或者my2. 不會是application
Spring 加載配置文件順序
- application.properties是最先加載的,相同類似的還有application.yml , config/application.properties , application-${profile}.properties
- 其他property
- @ImportResource引入的xml
為什么會有這種問題
如果一個key,user.name 在 application.properties內配置,同時又在xml引用的my.properties文件中引用,會造成在加載xml的Beanfatory中讀取到my.properties中的配置,非application.properties的配置
解決辦法
- 把application.properties配置到context:property-placeholder/解決,但這個會破壞springboot的profile特性,appliction-${profile}.properties/yml是應對多環境加載的一個優雅方案
- my.properties中的信息不配置,默認讀取application-${profile}.properties中的,只有1個項目沒有問題,涉及jar包傳遞的不好處理,具有局限性