How to let your spring boot pick up external property file

You may already see that ./config/application.properties can override the default spring boot application.properties settings. But when you deploy your app to tomcat and with many other web app together, then you need to have unique properties files foe each app and also make external property file be picked up by web app.

So let us do something like this:

  1. Change in your java main code to let your app use a unique properties file instead of application.properties.
@SpringBootApplication
public class MyApplication {

    public static void main(String[] args) {
        System.setProperty("spring.config.name", "myapp");
        SpringApplication.run(MyApplication.class, args);
    }
}

For war version of tomcat:

public class ServletInitializer extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(MyApplication.class).properties("spring.config.name: myapp");
    }

}

Then name your properties file like: myapp.properties, instead of the default name.

2. Now let us also enable the external property file to override the default myapp.properties.

in Spring boot, it is just ./config/myapp.properties

For tomcat version, we need to add env variable to do this. Set a spring_config_location environment variable pointing to the folder that contains your myapp.properties file. In the case of Tomcat you can do this by adding the following line to your <TOMCAT_HOME>/bin/setenv.sh file (create the file if missing):

export spring_config_location=<TOMCAT_HOME>/conf/

Place the myapp.properties properties file in that folder <TOMCAT_HOME>/conf/.

So every app will looking into the conf folder to look for their unique properties file to load.

 

Refer to:

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

 

 

Advertisements