Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading 2 property files having same variable names in Spring

I am reading property files using below entry in my Spring xml.

<context:property-placeholder 
    location="classpath:resources/database1.properties,
              classpath:resources/licence.properties"/>

I am injecting this values in variable using xml entry or using @Value annotation.

<bean id="myClass" class="MyClass">
    <property name="driverClassName" value="${database.driver}" />
    <property name="url" value="${database.url}" />
    <property name="name" value="${database.name}" />
</bean>

I want to add a new property file(database2.properties) which has few same variable names as of database1.properties.

database1.properties:

database.driver=com.mysql.jdbc.Driver
database.url=jdbc:mysql://192.168.1.10/
database.name=dbname

database2.properties:

database.url=jdbc:mysql://192.168.1.50/
database.name=anotherdbname
database.user=sampleuser

You can see few property variables have same name like database.url, database.name in both the property files.

Is it possible to inject database.url of database2.properties?

Or I have to change variable names?

Thank you.

like image 393
Naman Gala Avatar asked Feb 11 '23 10:02

Naman Gala


2 Answers

You can do it by configuring two PropertyPlaceholderConfigurer. Usually there's only one instance that serves out all the properties, however, if you change the placeholderPrefix you can use two instances, something like

<bean id="firstPropertyGroup" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="locations" value="classpath:resources/database1.properties,
              classpath:resources/licence.properties" />
   <property name="placeholderPrefix" value="${db1."/>
</bean>

<bean id="secondPropertyGroup" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="locations" value="classpath:resources/database2.properties" />
  <property name="placeholderPrefix" value="${db2."/>"
</bean>

Then you would access your properties like ${db1.database.url} or ${db2.database.url}

like image 118
Master Slave Avatar answered Feb 13 '23 00:02

Master Slave


There might be a solution, similar to what's that you want to achieve. Check the second answer to this question: Multiple properties access. It basically explains what to do in order to access the properties of the second file by using another expression, which is defined by you. Otherwise, the simplest solution would be just changing the key values (the variable names).

like image 25
Endrik Avatar answered Feb 12 '23 22:02

Endrik