【问题标题】:What is property resolution order in Spring property placeholder configurer with multiple locations?具有多个位置的 Spring 属性占位符配置器中的属性解析顺序是什么?
【发布时间】:2012-12-20 23:18:30
【问题描述】:

假设我有一个配置:

    <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?是否有任何已定义的属性解析顺序?

【问题讨论】:

标签: java spring properties


【解决方案1】:

PropertiesLoaderSupport.setLocation 状态的 javadoc

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

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

注意:在后面的文件中定义的属性将覆盖早期文件中定义的属性,以防键重叠。因此,请确保最具体的文件是给定位置列表中的最后一个。

所以 second.properties 中 my.url 的值会覆盖 first.properties 中 my.url 的值。

【讨论】:

    【解决方案2】:

    最后一个获胜。

    假设我们有 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
    

    【讨论】:

      猜你喜欢
      • 2014-03-23
      • 1970-01-01
      • 2013-01-21
      • 1970-01-01
      • 1970-01-01
      • 2015-05-22
      • 2017-09-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多