Loading...

September 20, 2015

Spring Sweets: 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.

package com.mrhaki.spring

import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.CommandLineRunner
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.stereotype.Controller

@SpringBootApplication
@Controller
class Application implements CommandLineRunner {

    @Value('${sample.message:"default"}')
    String message

    @Override
    void run(final String... args) throws Exception {
        println "Spring Boot says: $message"
    }

    static void main(String[] args) {
        SpringApplication.run(Application, args)
    }

}

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

buildscript {
    repositories.jcenter()

    dependencies {
        classpath 'org.springframework.boot:spring-boot-gradle-plugin:1.2.5.RELEASE'
    }
}

apply plugin: 'groovy'
apply plugin: 'spring-boot'

repositories.jcenter()

dependencies {
    compile 'org.codehaus.groovy:groovy-all:2.4.4'
    compile 'org.springframework.boot:spring-boot-starter'
}

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

$ gradle -q bootRun
...
Spring Boot says: "default"
...
$ 

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

$ SAMPLE_MESSAGE="Message from env." gradle -q bootRun
...
Spring Boot says: Message from env.
...
$ 

Written with Spring Boot 1.2.5.RELEASE and Gradle 2.7.