Spring属性占位符配置器中的属性解析顺序是什么,当有多个位置时如何处理?

15

假设我有一个配置:

    <bean id="batchJobProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>first.properties</value>
            <value>second.properties</value>
        </list>
    </property>
</bean>

first.properties中有属性"my.url=first.url",second.properties中有属性"my.url=second.url"

那么"myUrl" bean将注入哪个值?是否有定义的属性解析顺序?


请查看此链接 - http://forum.springsource.org/showthread.php?36672-PropertyPlaceholderConfigurer-multiple-property-files - Avinash T.
2个回答

23

PropertiesLoaderSupport.setLocation的javadoc说明如下:

设置要加载的属性文件的位置。

可以指向传统的属性文件或遵循JDK 1.5的属性XML格式的XML文件。

注意:后续文件中定义的属性将覆盖前面文件中定义的属性,如果有重叠的键。因此,请确保最具体的文件是给定位置列表中的最后一个。

因此,在second.properties中my.url的值将覆盖first.properties中my.url的值。


9
最后一个获胜。
假设我们有props1.properties文件,其中包含以下内容:
prop1=val1

以及props2.properties

prop1=val2

以及 context.xml

<context:annotation-config />
<bean id="batchJobProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>/props1.properties</value>
            <value>/props2.properties</value>
        </list>
    </property>
</bean>
<bean class="test.Test1" /> 

然后。
public class Test1 {
    @Value("${prop1}")
    String prop1;

    public static void main(String[] args) throws Exception {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("/test1.xml");
        System.out.println(ctx.getBean(Test1.class).prop1);
    }

}

打印

val2

如果我们更改上下文为

        <list>
            <value>/props2.properties</value>
            <value>/props1.properties</value>
        </list>

相同的测试打印

val1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接