(Quick Reference) # 4.1 Basic Configuration Version: 6.0.0 ## Table of Contents ## 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:
    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:
Variable | Description
--- | ---
userHome | Location of the home directory for the account that is running the Grails application.
grailsHome | Location of the directory where you installed Grails. If the `GRAILS_HOME` environment variable is set, it is used.
appName | The application name as it appears in build.gradle.
appVersion | The application version as it appears in build.gradle.
For example:
    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:
    class MyController {
        def hello() {
            def recipient = grailsApplication.config.getProperty('foo.bar.hello')

            render "Hello ${recipient}"
        }
    }
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.
    class MyController {

        def hello(Recipient recipient) {
            //Retrieve Integer property 'foo.bar.max.hellos', otherwise use value of 5
            def max = grailsApplication.config.getProperty('foo.bar.max.hellos', Integer, 5)

            //Retrieve property 'foo.bar.greeting' without specifying type (default is String), otherwise use value "Hello"
            def greeting = grailsApplication.config.getProperty('foo.bar.greeting', "Hello")

            def message = (recipient.receivedHelloCount >= max) ?
              "Sorry, you've been greeted the max number of times" :  "${greeting}, ${recipient}"
            }

            render message
        }
    }
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:
    import grails.core.*

    class MyService {
        GrailsApplication grailsApplication

        String greeting() {
            def recipient = grailsApplication.config.getProperty('foo.bar.hello')
            return "Hello ${recipient}"
        }
    }
### GrailsConfigurationAware Interface Accessing configuration dynamically at runtime can have a small effect 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`:
    import grails.core.support.GrailsConfigurationAware

    class MyService implements GrailsConfigurationAware {

        String recipient

        String greeting() {
            return "Hello ${recipient}"
        }

        void setConfiguration(Config config) {
            recipient = config.getProperty('foo.bar.hello')
        }

    }
### Spring Value Annotation You can use Spring’s Value annotation to inject configuration values:
    import org.springframework.beans.factory.annotation.*

    class MyController {
        @Value('${foo.bar.hello}')
        String recipient

        def hello() {
            render "Hello ${recipient}"
        }
    }
| 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:
    production:
        dataSource:
            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
    bootRun {
        systemProperties = System.properties
    }
For testing the following will need to change the `test` task as follows
    test {
        systemProperties = System.properties
    }
### 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/2.7.12/reference/html/features.html#features.external-config.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 Since Grails 3.0, logging 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 the logger for Grails Artifact followed the convention `grails.app.<type>.<className>`, where type is the type of the artifact, for example, `controllers` or `services`, and `className` is the fully qualified 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.BookController` | `grails.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.BookController` | `com.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.BookService` | `grails.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.BookService` | `com.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.BookDetail` | `com.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.yml
    grails:
        exceptionresolver:
            params:
                exclude:
                    - password
                    - creditCard
Request parameter logging may be turned off altogether by setting the `grails.exceptionresolver.logRequestParameters` config property to false. The default value is true when the application is running in DEVELOPMENT mode and false for all other environments. grails-app/conf/application.yml
    grails:
        exceptionresolver:
            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
    logging:
        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:
    $ export LOGGING_CONFIG=/Users/me/config/logback.groovy
    $ ./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:
    grails:
        gorm:
            failOnError: true
and to enable failOnError for domain classes by package:
    grails:
        gorm:
            failOnError:
                - com.companyname.somepackage
                - com.companyname.someotherpackage
## 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:
    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. | Quick Reference (hide)