具有重叠位置的多个属性占位符不起作用



我有三个属性文件:

file1.属性包含:
propA=1

file2.properties包含:
propA=2 propB=2

file3.properties包含:
propA=3 propB=3 propC=3

以及两个应用程序上下文:

applicationContext1.xml 包含:
<context:property-placeholder location="classpath:file1.properties,classpath:file2.properties" ignore-resource-not-found="true" ignore-unresolvable="true" system-properties-mode="OVERRIDE"/>

applicationContext2.xml 包含:
<context:property-placeholder location="classpath:file2.properties,classpath:file3.properties" ignore-resource-not-found="true" ignore-unresolvable="true" system-properties-mode="OVERRIDE"/>

以及加载上下文并注入所有属性的测试。我的测试.java:

@Value("${propA}")
private String propA;
@Value("${propB}")
private String propB;
@Value("${propC}")
private String propC;

我得到以下值:

 propA=2
 propB=2
 propC=3

为什么"propA"和"propB"不是从file3.properties中获取的?

拥有多个属性占位符配置器并不像您假设的那样工作。没有属性覆盖功能。 第一个尝试并替换它能替换的东西,然后下一个用剩下的东西抓住机会,依此类推。如果要覆盖属性,最好定义具有多个源的属性 bean,例如:

<bean name="appProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">  
        <property name="locations">
            <list>
                <value>classpath:conf/app-defaults.properties</value>
                <value>file:${CATALINA_BASE}/conf/my-app.properties</value>                 
            </list>
        </property>
        <property name="ignoreResourceNotFound" value="true" />
    </bean>

上面的代码定义了一个具有缺省值的属性 bean,它来自类路径文件和一个可选的外部化文件,该文件覆盖缺省值并驻留在 tomcat 安装中。然后,您可以使用属性占位符,如下所示:

<context:property-placeholder properties-ref="appProperties" /> 

Applicationcontext2覆盖了applicationcontext1

要确认,请在file1.prop中添加一个新变量,该变量在另外两个 file2 和 file3 中不可用。

最新更新