Spicy Spring: Setting Configuration Properties Via Environment Variables

Spring Boot has many options for externalising the configuration of our application. One of the options it to use OS environment variables. We need to follow certain rules to name the environment variable and then Spring Boot will use the value of variable to set a configuration property. The property name must be in uppercase and any dots need to be replaced with underscores. For example the configuration property sample.message is set with the environment variable SAMPLE_MESSAGE. This feature can be useful in a continuous integration environment where we can set environment variables or just when developing locally. The nice thing is that this also works when we use the Spring Boot Gradle plugin. The environment variables are passed on to the Java process that the bootRun task starts.

The following source file is a simple Spring Boot command-line application. The sample.message property can be configured as by Spring. If there is no value set the default value "default" is used.

We use the following Gradle build file with the Spring Boot Gradle plugin:

If we run the bootRun task without any environment variables set we get the default value:

Now we run the same task but set the environment variable SAMPLE_MESSAGE:

Written with Spring Boot 1.2.5.RELEASE and Gradle 2.7.

Original article

This entry was posted in Spring and tagged , , by mrhaki. Bookmark the permalink.

About mrhaki

My name is Hubert A. Klein Ikkink also known as mrhaki. I work at the great IT company JDriven. Here I work on projects with Groovy & Grails, Gradle and Spring. At JDriven we focus on SpringSource technologies. All colleagues want to learn new technologies, support craftmanship and are very eager to learn. This is truly a great environment to work in. You can contact me via Google+ or @mrhaki.

Leave a Reply

Your email address will not be published. Required fields are marked *