Saturday, April 11, 2015

Programmatic access to the properties loaded by PropertySourcesPlaceholderConfigurer

     Some time ago I implemented a kind of info page for exposing actual application properties. In the application there was PropertySourcesPlaceholderConfigurer involved. It has some really nice features but it hides the properties from direct access. I had to overcome that difficulty in order to iterate over them.
Some folks suggested to use PropertiesLoaderUtils. However, it is not the same if you want to get access to the exact same properties which will be injected using @Value annotation. I always try to find the easiest solution possible according to the maxim by Mikhail Kalashnikov:
"All that is complex is not useful. All that is useful is simple." 
It appeared there was quite a simple way to achieve my goal:
public class CapturePropertySourcesPlaceholderConfigurer extends PropertySourcesPlaceholderConfigurer {

    private static final Properties PROPERTIES = new Properties();

    @Override
    protected void loadProperties(Properties props) throws IOException {
        super.loadProperties(props);
        PROPERTIES.putAll(props);
    }

    public static String getProperty(String name, String defaultValue) {
        return fromNullable(PROPERTIES.getProperty(name)).or(defaultValue);
    }
}
Now, instead of using PropertySourcesPlaceholderConfigurer you can utilize CapturePropertySourcesPlaceholderConfigurer to obtain direct access to your properties. Have fun!

No comments :

Post a Comment