Tuesday, April 24, 2012

Using Variable Substitution from Configuration Files in Spring

It doesn't take long in the development world to learn that hard coding property values is a bad idea.  Hard coded values will require the software to be rebuilt and redeployed if a change is required.   Moving values to configuration files so they can be modified in a central location is a first step.  A second step is moving the configuration file outside of the .war or .ear, so they can be modified at run time to avoid recompiling.  To read about how to externalize property files from your application see my earlier blog.

There are several places in the Spring configuration that can make use of variable substitution from a property file.  First things first. If you create a property file how do you access it from your spring configuration file?  Near the top of the configuration file add the following bean definition:

    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
         <property name="locations">

If you need to have comments in the property file, start the line with a #.  Properties should be entered into the property file in the following format: property.name=property value, i.e.


Properties can be referenced from value fields, as well as bean variables.

	<bean id="jmsQueue" class="org.springframework.jndi.JndiObjectFactoryBean">
		<property name="jndiName" value="${my.project.testQueue}"/>
		<property name="jndiTemplate" ref="jndiTemplate" />
	<si-ws:outbound-gateway id="WebServiceGateway"
			 uri="${my.project.uri}"  />

It is also possible to access properties from spring annotations which can be very useful. The scheduled annotation is a good example.


Spring makes it very easy to leverage properties files for making systems easier to configure on the fly. There is no need to continue hard coding values that you or your client may want to change.

1 comment:

AXN said...

I am trying to use placeholderconfigurer in spring, but i want the properties file outside jar.ie., properties file is in same fodler as jar. How do i specify the location in placeholderconfigurer bean of spring