Loading...

September 28, 2015

Grails Goodness: Use Different External Configuration Files

A Grails 3 application uses the same mechanism to load external configuration files as a Spring Boot application. This means the default locations are the root directory or config/ directory in the class path and on the file system. If we want to specify a new directory to search for configuration files or specify the configuration files explicitly we can use the Java system property spring.config.location.

In the following example we have a configuration application.yml in the settings directory. The default base name for a configuration file is application, so we use that base name in our example. In this sample we use a YAML configuration file where we override the property sample.config for the Grails production environment.

# File: settings/application.yml
sample:
  config: From settings/.

---
environments:
  production:
    sample:
      config: From settings/ dir and production env.

Next we need to reconfigure the run and bootRun tasks, both of type JavaExcec, to pass on Java system properties we use from the command line when we use the Grails commands:

// File: build.gradle
...
tasks.withType(JavaExec).each { task ->
    task.systemProperties System.properties
}

Now we can start our Grails application with the Java system property spring.config.location. We add the settings directory as a search location for configuration files. We add both the directory as a local directory as well as a root package name in the class path:

$ grails -Dspring.config.location=settings/,classpath:/settings/ run-app
...

In the following example we have a configuration config.yml in the root of our project:

# File: config.yml
sample:
  config: From config.yml.

---
environments:
  production:
    sample:
      config: From config.yml dir and production env.

Now we start Grails and use the explicit file name as a value for the Java system property spring.config.location:

$ grails -Dspring.config.location=file:./config.yml run-app
...

We could specify multiple files separated by comma's. Or even combine it with directories like we used in the first example.

Written with Grails 3.0.8.