什么是具有多个位置的Spring属性占位符配置器中的属性解析顺序?

Vla*_*mir 13 java spring properties

让我们说我有一个配置:

    <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>
Run Code Online (Sandbox Code Playgroud)

first.properties具有属性"my.url = first.url"second.properties具有属性"my.url = second.url"

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

Mar*_*ark 20

PropertiesLoaderSupport.setLocation的javadoc 状态

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

可以指向经典属性文件或遵循JDK 1.5属性XML格式的XML文件.

注意:在重叠键的情况下,在以后的文件中定义的属性将覆盖先前定义的文件的属性.因此,请确保最具体的文件是给定位置列表中的最后一个文件.

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


Evg*_*eev 7

最后一个获胜.

假设我们有props1.properties为

prop1=val1
Run Code Online (Sandbox Code Playgroud)

和props2.properties

prop1=val2
Run Code Online (Sandbox Code Playgroud)

和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" /> 
Run Code Online (Sandbox Code Playgroud)

然后

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);
    }

}
Run Code Online (Sandbox Code Playgroud)

版画

VAL2

如果我们改变上下文

        <list>
            <value>/props2.properties</value>
            <value>/props1.properties</value>
        </list>
Run Code Online (Sandbox Code Playgroud)

相同的测试打印

val1
Run Code Online (Sandbox Code Playgroud)