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

I ran into a simple problem here. I have two properties files that I want to read in order to create two data sources. But these property files have exactly the same keys! I can read both files using:

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

But then I can not access the correct 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 to use variables like ${foo1.driver} and know which one is being called?

Thanks for the help!

+6
source share
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> 
+6
source

I assume that I will make this extension PropertyPlaceHolderConfigurer.

It seems to me that you should override the PropertiesLoaderSupport.loadProperties(Properties) method

What I would do is add the prefix property

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

And repeat these prefixes when reading Properties resources.

+1
source

Source: https://habr.com/ru/post/914815/


All Articles