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.
Another way is to split the definition of the properties and the bean configuration process.
ReplyDelete<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/