Override Property value in PropertyPlaceholderConfigurer

2.2k views Asked by At

I need to override a property value given in my property file while loading my JBOSS Application server.

I tried out with below code overriding processProperties() method in PropertyPlaceholderConfigurer.

My property file has this entry

base.url="defaultUrl"

public class CustomPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {

protected String convertPropertyValue(String originalValue) {
    return (originalValue != null) ? originalValue.trim() : originalValue;
}

@Override
protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties props)
        throws BeansException {
    super.processProperties(beanFactory, props);
    for (Enumeration names = props.propertyNames(); names.hasMoreElements();) {
        String key = (String) names.nextElement();
        props.put("base.url", getUpdatedUrl());
    }
}

}

I am injecting base.url value in a placeholder ${base.url} in application context.

How should I update the value of given property in run time. The above code always take the value in the property file not the updated value.

1

There are 1 answers

0
wi2ard On

Blowing the dust off from this question. This can be done using PropertyPlaceholderConfigurer and adding a new property file (at the end of the list), where you put the properties you want to override. (The name/file path of the property file can contain an environment variable you pass at build time). Here's the javadoc of PropertiesLoaderSupport#setLocations:

Note: Properties defined in later files will override properties defined earlier files, in case of overlapping keys. Hence, make sure that the most specific files are the last ones in the given list of locations.

As of Spring 5.2 this was deprecated in favor of PropertySourcesPlaceholderConfigurer:

Specialization of PlaceholderConfigurerSupport that resolves ${...} placeholders within bean definition property values and @Value annotations against the current Spring Environment and its set of PropertySources.

Some examples here