Environment based Properties in Spring Boot

The adoption of Spring Boot in both small and large scale software proved that convention over configuration is the chosen approach for many developers. Spring Boot provides sane defaults and has allowed us to rapidly iterate our development cycles without worrying about configuration. One of the things that Spring excels is the annotation “magic”. Using annotations, you can inject property variables, autowire dependencies and what not. Recently, we wanted to deploy a Spring Boot based POS solution and came across the problem of setting properties file dynamically.

Dev/Stage/Prod which file to use when?

The problem was to use the correct properties file based on the environment. The production server has a different set of properties (like DB, Logging etc) than the dev/staging environment. We had to manually change the properties file location in the code on the server which was a no-go.

Placeholders to the rescue

Spring allows placeholders to be put in the @PropertySource annotation which loads the properties file. By specifying the file path and spring.profiles.active from command line options (-D) when running the executable Jar file, we can load the external properties file easily.

Show me the code

public class FashtagApplication {

    private String property1;

    private String property2;

In the code above, $(props.path) and $(spring.profiles.active) act as placeholders and are replaced by the options that we pass along with -D in the command line.

gt; java -Dprops.path=some/path -Dspring.profiles.active=dev -jar myApp.jar
This will load the application-dev.properties located at some/path. This solves two purposes, you can set the currently active profile to be used elsewhere by Spring and you can set the customized path of the properties file. This allows separate properties for production, staging and dev environments.