What is property resolution order in Spring property placeholder configurer with multiple locations?

后端 未结 2 1118
南方客
南方客 2021-01-04 05:05

Lets say I have a configuration:

    
         


        
相关标签:
2条回答
  • 2021-01-04 05:23

    The javadoc for PropertiesLoaderSupport.setLocation states

    Set locations of properties files to be loaded.

    Can point to classic properties files or to XML files that follow JDK 1.5's properties XML format.

    Note: Properties defined in later files will override properties defined earlier files, in case of overlapping keys. Hence, make sure that the most specific files are the last ones in the given list of locations.

    So the value of my.url in second.properties will override the value of my.url in first.properties.

    0 讨论(0)
  • 2021-01-04 05:34

    The last one wins.

    Assuming we have props1.properties as

    prop1=val1
    

    and props2.properties

    prop1=val2
    

    and 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" /> 
    

    then

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

    prints

    val2

    and if we change context as

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

    the same test prints

    val1
    
    0 讨论(0)
提交回复
热议问题