Books I Like

Monday, October 5, 2009

Recipe : How to get property value in a Spring Application

If you work with Spring, I am sure you might have come across the scenario when you need to access the value of a property key in your application.

The class "org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" is normally used to resolve the runtime key/value pairs. However, if you need to use a property value in your bean, it doesn't expose that to be read.

Here is a very simple work-around :-

1. Extend the PropertyPlaceholderConfigurer


public class OpenPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {

Properties mergedProperties;

public Properties getMergedProperties() throws IOException {
if (mergedProperties == null) {

mergedProperties = mergeProperties();

}
return mergedProperties;

}
}



2. Configure it to be used instead of PropertyPlaceholderConfigurer

  
<bean id="propertyConfigurer" class="com.mypackage.OpenPropertyPlaceholderConfigurer">
<property name="ignoreResourceNotFound" value="false"/>
<property name="locations">
<list>
<value>classpath:common.properties</value>
<value>classpath:${YOUR_ENV}.properties</value>
</list>
</property>
</bean>


3. Inject this "propertyConfigurer" in your defined bean.

4. Get the key value propertyConfigurer.getMergedProperties().getProperty("your.prop.key")

I am sure, there could be some better ways. Let me know, if you know one.

Credit goes to Mat for this recipe.

1 comment:

Freaky-namuH said...

Another way is to split the definition of the properties and the bean configuration process.

<bean
id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property
name="systemPropertiesModeName"
value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property
name="properties"
ref="applicationProperties" />
</bean>

<bean
id="applicationProperties"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property
name="locations">
<list>
<value>classpath:common.properties</value>
<value>classpath:${YOUR_ENV}.properties</value>
</list>
</property>
</bean>

And then just use the applicationProperties bean itself.

http://www.surgbase.com.au/

Get at Amazon