Search code examples
javaspringspring-properties

Custom Property Management with Spring 4.x


Reading this and that I could easily customize my environment in a web-app.

My customization is pretty simple, I have some property files packaged in my deployable war file and I would like to have a local properties file on my web-server machine that will override those properties in case of overlap. To do that I implemented the ApplicationContextInitializer interface, loaded my local properties file and used the addFirst method of my environment. This made sure my local file overrides the properties files packed in my war.

This worked perfectly. Now I would like to do the same in a java-spring process (not a web-app), How can I do that?

The best solution I have found so far is to add a method to my configuration class and annotate it with the @PostConstruct annotation. This method does exactly what the initialize method of ApplicationContextInitializer.

This solution doesn't serve my needs since I have some beans that are loaded conditionally and this (the conditional annotation code) happens before my @postConstruct method (which is not good since the conditional loading is based upon my properties).


Solution

  • I got over it by loading multiple property-sources:

    @Configuration
    @ComponentScan("com.company.project")
    @PropertySources({ @PropertySource(value = "classpath:/my-jar-properties-file.properties", ignoreResourceNotFound = false),
        @PropertySource(value = "file:/path/to/file/local.filesystem.properties.file.properties", ignoreResourceNotFound = false) })
    public class MyConfiguration { ... }
    

    This way the last properties file will override the previous ones, so simple..