4.1 Basic Configuration

Configuration in Grails is generally split across 2 areas: build configuration and runtime configuration.

Build configuration is generally done via Gradle and the build.gradle file. Runtime configuration is by default specified in YAML in the grails-app/conf/application.yml file.

If you prefer to use Grails 2.0-style Groovy configuration then it is possible to specify configuration using Groovy’s ConfigSlurper syntax. Two Groovy configuration files are available: grails-app/conf/application.groovy and grails-app/conf/runtime.groovy:

  • Use application.groovy for configuration that doesn’t depend on application classes

  • Use runtime.groovy for configuration that does depend on application classes

This separation is necessary because configuration values defined in application.groovy are available to the Grails CLI, which needs to be able to load application.groovy before the application has been compiled. References to application classes in application.groovy will cause an exception when these commands are executed by the CLI:
  1. Error occurred running Grails CLI:startup failed:script14738267015581837265078.groovy: 13: unable to resolve class com.foo.Bar

For Groovy configuration the following variables are available to the configuration script:

VariableDescription
userHomeLocation of the home directory for the account that is running the Grails application.
grailsHomeLocation of the directory where you installed Grails. If the GRAILS_HOME environment variable is set, it is used.
appNameThe application name as it appears in build.gradle.
appVersionThe application version as it appears in build.gradle.

For example:

  1. my.tmp.dir = "${userHome}/.grails/tmp"

Accessing Configuration with GrailsApplication

If you want to read runtime configuration settings, i.e. those defined in application.yml, use the grailsApplication object, which is available as a variable in controllers and tag libraries:

  1. class MyController {
  2. def hello() {
  3. def recipient = grailsApplication.config.getProperty('foo.bar.hello')
  4. render "Hello ${recipient}"
  5. }
  6. }

The config property of the grailsApplication object is an instance of the Config interface and provides a number of useful methods to read the configuration of the application.

In particular, the getProperty method (seen above) is useful for efficiently retrieving configuration properties, while specifying the property type (the default type is String) and/or providing a default fallback value.

  1. class MyController {
  2. def hello(Recipient recipient) {
  3. //Retrieve Integer property 'foo.bar.max.hellos', otherwise use value of 5
  4. def max = grailsApplication.config.getProperty('foo.bar.max.hellos', Integer, 5)
  5. //Retrieve property 'foo.bar.greeting' without specifying type (default is String), otherwise use value "Hello"
  6. def greeting = grailsApplication.config.getProperty('foo.bar.greeting', "Hello")
  7. def message = (recipient.receivedHelloCount >= max) ?
  8. "Sorry, you've been greeted the max number of times" : "${greeting}, ${recipient}"
  9. }
  10. render message
  11. }
  12. }

Notice that the Config instance is a merged configuration based on Spring’s PropertySource concept and reads configuration from the environment, system properties and the local application configuration merging them into a single object.

GrailsApplication can be easily injected into services and other Grails artifacts:

  1. import grails.core.*
  2. class MyService {
  3. GrailsApplication grailsApplication
  4. String greeting() {
  5. def recipient = grailsApplication.config.getProperty('foo.bar.hello')
  6. return "Hello ${recipient}"
  7. }
  8. }

GrailsConfigurationAware Interface

Accessing configuration dynamically at runtime can have a small affect on application performance. An alternative approach is to implement the GrailsConfigurationAware interface, which provides a setConfiguration method that accepts the application configuration as a parameter when the class is initialized. You can then assign relevant configuration properties to instance properties on the class for later usage.

The Config instance has the same properties and usage as the injected GrailsApplication config object. Here is the service class from the previous example, using GrailsConfigurationAware instead of injecting GrailsApplication:

  1. import grails.core.support.GrailsConfigurationAware
  2. class MyService implements GrailsConfigurationAware {
  3. String recipient
  4. String greeting() {
  5. return "Hello ${recipient}"
  6. }
  7. void setConfiguration(Config config) {
  8. recipient = config.getProperty('foo.bar.hello')
  9. }
  10. }

Spring Value Annotation

You can use Spring’s Value annotation to inject configuration values:

  1. import org.springframework.beans.factory.annotation.*
  2. class MyController {
  3. @Value('${foo.bar.hello}')
  4. String recipient
  5. def hello() {
  6. render "Hello ${recipient}"
  7. }
  8. }
In Groovy code you must use single quotes around the string for the value of the Value annotation otherwise it is interpreted as a GString not a Spring expression.

As you can see, when accessing configuration settings you use the same dot notation as when you define them.

4.1.1 Options for the YML format Config

The application.yml file was introduced in Grails 3.0, and YAML is now the preferred format for configuration files.

Using system properties / command line arguments

Suppose you are using the JDBC_CONNECTION_STRING command line argument and you want to access the same in the yml file then it can be done in the following manner:

  1. production:
  2. dataSource:
  3. url: '${JDBC_CONNECTION_STRING}'

Similarly system arguments can be accessed.

You will need to have this in build.gradle to modify the bootRun target if grails run-app is used to start the application

  1. bootRun {
  2. systemProperties = System.properties
  3. }

For testing the following will need to change the test task as follows

  1. test {
  2. systemProperties = System.properties
  3. }

External configuration

Grails will read application.(properties|yml) from the ./config or the current directory by default.As Grails is a SpringBoot configuration options are available as well, for documentation please consult: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-application-property-files

4.1.2 Built in options

Grails has a set of core settings that are worth knowing about. Their defaults are suitable for most projects, but it’s important to understand what they do because you may need one or more of them later.

Runtime settings

On the runtime front, i.e. grails-app/conf/application.yml, there are quite a few more core settings:

  • grails.enable.native2ascii - Set this to false if you do not require native2ascii conversion of Grails i18n properties files (default: true).

  • grails.views.default.codec - Sets the default encoding regime for GSPs - can be one of 'none', 'html', or 'base64' (default: 'none'). To reduce risk of XSS attacks, set this to 'html'.

  • grails.views.gsp.encoding - The file encoding used for GSP source files (default: 'utf-8').

  • grails.mime.file.extensions - Whether to use the file extension to dictate the mime type in Content Negotiation (default: true).

  • grails.mime.types - A map of supported mime types used for Content Negotiation.

  • grails.serverURL - A string specifying the server URL portion of absolute links, including server name e.g. grails.serverURL="http://my.yourportal.com". See createLink. Also used by redirects.

  • grails.views.gsp.sitemesh.preprocess - Determines whether SiteMesh preprocessing happens. Disabling this slows down page rendering, but if you need SiteMesh to parse the generated HTML from a GSP view then disabling it is the right option. Don’t worry if you don’t understand this advanced property: leave it set to true.

  • grails.reload.excludes and grails.reload.includes - Configuring these directives determines the reload behavior for project specific source files. Each directive takes a list of strings that are the class names for project source files that should be excluded from reloading behavior or included accordingly when running the application in development with the run-app command. If the grails.reload.includes directive is configured, then only the classes in that list will be reloaded.

4.1.3 Logging

By default logging in Grails 3.0 is handled by the Logback logging framework and can be configured with the grails-app/conf/logback.groovy file.

If you prefer XML you can replace the logback.groovy file with a logback.xml file instead.

For more information on configuring logging refer to the Logback documentation on the subject.

4.1.3.1 Logger Names

Grails artifacts (controllers, services …​) get injected a log property automatically.

Prior to Grails 3.3.0, the name of thelogger for Grails Artifact followed the convention grails.app.<type>.<className>, where type is thetype of the artifact, for example, controllers or services, and className is the fullyqualified name of the artifact.

Grails 3.3.x simplifies logger names. The next examples illustrate the changes:

BookController.groovy located at grails-app/controllers/com/company NOT annotated with @Slf4j

Logger Name (Grails 3.3.x or higher)Logger Name (Grails 3.2.x or lower)
com.company.BookControllergrails.app.controllers.com.company.BookController

BookController.groovy located at grails-app/controllers/com/company annotated with @Slf4j

Logger Name (Grails 3.3.x or higher)Logger Name (Grails 3.2.x or lower)
com.company.BookControllercom.company.BookController

BookService.groovy located at grails-app/services/com/company NOT annotated with @Slf4j

Logger Name (Grails 3.3.x or higher)Logger Name (Grails 3.2.x or lower)
com.company.BookServicegrails.app.services.com.company.BookService

BookService.groovy located at grails-app/services/com/company annotated with @Slf4j

Logger Name (Grails 3.3.x or higher)Logger Name (Grails 3.2.x or lower)
com.company.BookServicecom.company.BookService

BookDetail.groovy located at src/main/groovy/com/company annotated with @Slf4j

Logger Name (Grails 3.3.x or higher)Logger Name (Grails 3.2.x or lower)
com.company.BookDetailcom.company.BookDetail

4.1.3.2 Masking Request Parameters From Stacktrace Logs

When Grails logs a stacktrace, the log message may include the names and values of all of the request parameters for the current request.To mask out the values of secure request parameters, specify the parameter names in the grails.exceptionresolver.params.exclude config property:

grails-app/conf/application.yaml

  1. grails:
  2. exceptionresolver:
  3. params:
  4. exclude:
  5. - password
  6. - creditCard

Request parameter logging may be turned off altogether by setting the grails.exceptionresolver.logRequestParametersconfig property to false. The default value is true when the application is running in DEVELOPMENT mode and false for all otherenvironments.

grails-app/conf/application.yaml

  1. grails:
  2. exceptionresolver:
  3. logRequestParameters: false

4.1.3.3 External Configuration File

If you set the configuration property logging.config, you can instruct Logback to use an external configuration file.

grails-app/conf/application.yml

  1. logging:
  2. config: /Users/me/config/logback.groovy

Alternatively, you can supply the configuration file location with a system property:

$ ./gradlew -Dlogging.config=/Users/me/config/logback.groovy bootRun

Or, you could use an environment variable:

  1. $ export LOGGING_CONFIG=/Users/me/config/logback.groovy
  2. $ ./gradlew bootRun

4.1.4 GORM

Grails provides the following GORM configuration options:

  • grails.gorm.failOnError - If set to true, causes the save() method on domain classes to throw a grails.validation.ValidationException if validation fails during a save. This option may also be assigned a list of Strings representing package names. If the value is a list of Strings then the failOnError behavior will only be applied to domain classes in those packages (including sub-packages). See the save method docs for more information.

For example, to enable failOnError for all domain classes:

  1. grails:
  2. gorm:
  3. failOnError: true

and to enable failOnError for domain classes by package:

  1. grails:
  2. gorm:
  3. failOnError:
  4. - com.companyname.somepackage
  5. - com.companyname.someotherpackage
  • grails.gorm.autoFlush - If set to true, causes the merge, save and delete methods to flush the session, replacing the need to explicitly flush using save(flush: true).

4.1.5 Configuring an HTTP proxy

To setup Grails to use an HTTP proxy there are two steps. Firstly you need to configure the grails CLI to be aware of the proxy if you wish to use it to create applications and so on. This can be done using the GRAILS_OPTS environment variable, for example on Unix systems:

  1. export GRAILS_OPTS="-Dhttps.proxyHost=127.0.0.1 -Dhttps.proxyPort=3128 -Dhttp.proxyUser=test -Dhttp.proxyPassword=test"
The default profile repository is resolved over HTTPS so https.proxyPort and https.proxyUser are used, however the username and password are specified with http.proxyUser and http.proxyPassword

For Windows systems the environment variable can be configured under My Computer/Advanced/Environment Variables.

With this configuration in place the grails command can connect and authenticate via a proxy.

Secondly, since Grails uses Gradle as the build system, you need to configure Gradle to authenticate via the proxy. For instructions on how to do this see the Gradle user guide section on the topic.