Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read multiple properties having the same keys in Spring?

Tags:

java

spring

I am facing a simple problem here. I have two properties files I want to read to create two datasources. Yet those properties files have exactly the same keys! I am able to read both the files using:

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

But then I am not able to access the right value:

<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>

How can I read my properties so that I can use variables such as ${foo1.driver} and know which one is called?

Thanks for helping!

like image 567
Jean Logeart Avatar asked May 03 '12 14:05

Jean Logeart


2 Answers

Try something like this(not tested):

<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>
like image 183
Luca Avatar answered Oct 01 '22 08:10

Luca


I guess what I'd do is extend PropertyPlaceHolderConfigurer.

To me it looks like you have to override the method PropertiesLoaderSupport.loadProperties(Properties)

What I'd do is add a property "prefixes"

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

And iterate over these prefixes while reading the Properties resources.

like image 34
Sean Patrick Floyd Avatar answered Oct 01 '22 08:10

Sean Patrick Floyd