【问题标题】:How to read multiple properties having the same keys in Spring?如何在 Spring 中读取具有相同键的多个属性?
【发布时间】:2012-05-03 14:11:53
【问题描述】:

我在这里面临一个简单的问题。我有两个要读取的属性文件来创建两个数据源。然而,这些属性文件具有完全相同的键!我可以使用以下方式读取这两个文件:

<context:property-placeholder 
    location="classpath:foo1.properties,classpath:foo2.properties"/>

但是我无法访问正确的值:

<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close">
    <property name="driverClassName" value="${driver}" /> <!-- Which one? -->
    <property name="url" value="${url}" />                <!-- Which one? -->
    ...
</bean>

如何读取我的属性,以便我可以使用诸如${foo1.driver} 之类的变量并知道调用了哪个变量?

感谢您的帮助!

【问题讨论】:

    标签: java spring


    【解决方案1】:

    试试这样的(未测试):

    <bean id="config1" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
           <property name="ignoreUnresolvablePlaceholders" value="true"/>
           <property name="placeholderPrefix" value="${foo1."/>
           <property name="locations">
            <list>
              <value>classpath:foo1.properties</value>
            </list>
          </property>
        </bean>
    
        <bean id="config2" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
           <property name="ignoreUnresolvablePlaceholders" value="false"/>
           <property name="placeholderPrefix" value="${foo2."/>
           <property name="locations">
            <list>
              <value>classpath:foo2.properties</value>
            </list>
          </property>
        </bean>
    

    【讨论】:

      【解决方案2】:

      我想我要做的是扩展 PropertyPlaceHolderConfigurer。

      在我看来,您必须重写方法 PropertiesLoaderSupport.loadProperties(Properties)

      我要做的是添加一个属性“前缀”

      public void setPrefixes(List<String> prefixes){
          this.prefixes = prefixes;
      }
      

      并在读取属性资源时遍历这些前缀。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-06-22
        • 1970-01-01
        • 1970-01-01
        • 2018-08-05
        • 2019-06-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多