Grails Goodness: Pass Configuration Values Via Environment Variables
Since Grails 3 is based on Spring Boot we can re-use many of the Spring Boot features in our Grails application. For example in a Spring Boot application we can use environment variables to give configuration properties a value. We simply need to follow some naming rules: the name of the configuration property must be in uppercase and dots are replaced with underscores. For example a configuration property feature.enabled
is represented by the environment variable FEATURE_ENABLED
.
We create the following controller in a Grails 3 application with a message
property. The value is set with the @Value
annotation of the underlying Spring framework. With this annotation we tell the application to look for an (external) configuration property sample.message
and assign it's value to the message
property. If it cannot be set via a configuration property the default value is "gr8".
package com.mrhaki.grails
import org.springframework.beans.factory.annotation.Value
class SampleController {
@Value('${sample.message:gr8}')
String message
def index() {
render "Grails is ${message}!"
}
}
If we run the application with grails run-app
or gradle run
the result of opening http://localhost:8080/sample
is Grails is gr8!
.
Now we use the environment variable SAMPLE_MESSAGE
to assign a new value to the message
property:
$ SAMPLE_MESSAGE=great grails run-app
...
Grails application running at http://localhost:8080 in environment: development
Now when we access http://localhost:8080/sample
we get Grails is great!
. If we use Gradle to start our Grails application we can use SAMPLE_MESSAGE=great gradle run
.
Written with Grails 3.0.7.