Friday, April 4, 2008

Java Spring Framework : Multiple PropertyPlaceholderConfigurer configurtion

This is very small thing which can be very annoying while coding in spring framework. Of cource no one can directly understand the problem until he faced that.

At first, I had only one property file from which i am reading some values into spring applicationContext Xml configuration file.So when i needed to add second one for my new feature, i think it is just to add new propertyPlaceholderConfigurer bean with second prop file.

my first prop file 'default-prop.properties' is :
default-prop.custName=testing customer
default-prop.address=building1
and the bean definition in the applicationContext xml file for this is:

<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>classpath:default-prop.properties</value>
</property>
</bean>

so while adding second one, i have just added second bean for it like:
<bean id="propertyConfigurerNew"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>classpath:second-prop.properties</value>
</property>
</bean>
and in xml, prop has been read as,
<property name="customerName" value="${default-prop.custName}" />
But when i done this, i got error
"Could not resolve placeholder 'default-prop.custName' "
So i have to do some workaround and digg into spring references. And i found that we can define seperate placeHolderPrefix and suffix for each property configurer bean.

I have changed the bean definition as,
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>classpath:default-prop.properties</value>
</property>
<property name="placeholderPrefix" value="${" />
<property name="placeholderSuffix" value="}" />
</bean>

<bean id="propertyConfigurerNew"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>classpath:second-prop.properties</value>
</property>
<property name="placeholderPrefix" value="#[" />
<property name="placeholderSuffix" value="]" />
</bean>
it means, for first prop bean, we will use ${default-prop.custName} and for second bean we will use #[second-prop.secondName]

And voila! it solved my problem...

You can also use
<property name="ignoreUnresolvablePlaceholders" value="true" />
for each PropertyPlaceholderConfigurer bean defined. But, i have used the prefix-suffix one solution.
And my problem is resolved.

Give your comments on this problem and solution.

1 Comment:

Anonymous said...

You could use PropertyPlaceholderConfigurer.setLocations() to setup multiple property files and use setIgnoreResourceNotFound to ignore the unavailable property file to ignore the if the file is not found, instead of changing the prefix/suffix.