Search

Dark theme | Light theme

September 21, 2015

Spring Sweets: Java System Properties As Configuration Properties With Spring Boot

In a previous post we learned that configuration property values can be passed via environment variables. With Spring Boot we can also pass the values using Java system properties. So if we have a property sample.message then we can use -Dsample.message=value to pass a value when we run the application. If we use the Spring Boot Gradle plugin we must reconfigure the bootRun task to pass Java system properties from the command-line.

Let's reuse our sample application from the previous blog post:

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)
    }

}

Our Gradle build file now looks like this:

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'
}

// Reconfigure bootRun task to pass
// along the Java system properties
// from the command-line.
bootRun {
    systemProperties System.properties
}

Now we can run the following command from the command-line and set a value for the sample.message configuration property:

$ gradle -Dsample.message="Set by Java sys prop." -q bootRun
...
Spring Boot says: Set by Java sys prop.
...
$ 

Written with Spring Boot 1.2.5.RELEASE and Gradle 2.7.