Books I Like

Showing posts with label Properties. Show all posts
Showing posts with label Properties. Show all posts

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.

Get at Amazon