Tuesday, February 05, 2008

Environment specific properties - the spring way.

This problem is easily solved via the use of 2 Spring IoC bean post-processor classes viz:

org.springframework.beans.factory.config.PropertyPlaceholderConfigurer
org.springframework.beans.factory.config.PropertyOverrideConfigurer


To use this functionality you would need to have them declared in your app-context config files
as follows:


<bean id="ppConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="order" value="1" />
<property name="locations">
<list>
<value>classpath:ppc-sample.properties</value>
</list>

</property>

</bean>
<bean id="poConfigurer"
class="org.springframework.beans.factory.config.PropertyOverrideConfigurer">
<property name="location"
value="classpath:poc-sample-${my.env}.properties" />
<property name="order" value="10" />
<property name="ignoreResourceNotFound" value="true" />
</bean>


They are like any other bean definitions but there are few properties in their definitions that need special attention
as they are responsible for the magic. They are order, location and ignoreResourceNotFound.


order - determines how these post processors are loaded or applied to beans via Spring IoC.
location - (atleast in the case of the PropertyOverrideConfigurer bean) matters because of the use of an ant/JSTL/groovy property.
This is where the PropertyPlaceholderConfigurer comes in. It is used to define the default value for the my.env environment variable. Without this the PropertyOverrideConfigurer will have problems when Spring tries to load it.
ignoreResourceNotFound - makes sure there are no complaints by Spring when initialising the PropertyOverrideConfigurer bean.

Any bean where you want to use environment specific values can now be defined in your poc-sample-${my.env}.properties file.
Given the following bean configurations where you wish to use this functionality

<bean id="myBean" class="com.lhfville.sample.POC"
lazy-init="true">
<property name="prop1" value="${prop1}" />
</bean>

<bean id="myBean" class="com.lhfville.sample.POC"
lazy-init="true">
<property name="prop1" value="hi" />
</bean>

you can have poc-sample-dev.properties poc-sample-test.properties poc-sample-prod.properties files in your classpath with varying values for myBean.prop1.


Thats pretty much it.

1 comment:

Anonymous said...

How would I represent
property name="prop1" value="hi"

in annotation?