Application configurations setting in Grails 3

09 / Jun / 2015 by Uday Pratap Singh 1 comments

Grails has done lot of changes with its latest release in Grails 3, using configuration is one of them.
Now we can write application configurations in application.yml and application.groovy as well and to read these property we can need to write the following code.

class ExampleController {

    GrailsApplication grailsApplication

    def index() {
        render "Old way ${grailsApplication.config.grails.project.groupId}"
        render "New way ${grailsApplication.config.getProperty('grails.project.groupId')}"
    }

}

Since Grails 3 is built on Spring boot so we can use Spring way of configuration as well using a simple annotation.

import org.springframework.beans.factory.annotation.Value

class ExampleController {

    @Value('${grails.project.groupId}')
    String groupId

    def index() {
        render "Controller ${groupId}"
    }

Using the annotation based configuration the application will read configuration from the environment, system properties and the local application configuration merging them into a single object. So if you have set the environment variable e.g; GRAILS_PROJECT_GROUPID it will override the local application configuration variable.

Writting the same variable configuration in every controller isn’t a very nice way so we can create a service which will return the config variables to us like following

import org.springframework.beans.factory.annotation.Value

class ApplicationConfigService {
    static transactional = false

    @Value('${grails.project.groupId}')
    String groupId
}

class ExampleController {

    ApplicationConfigService appConfigService

    def index() {
        render "Service ${appConfigService.groupId}"
    }

    def setConfig(String value) {
        appConfigService.groupId = value
        render "Config set to ${appConfigService.groupId}"
    }

}

Now we have a separate code to read and set the application variable without any methods just simple annotations.

Hope it helps
Reference http://grails.github.io/grails-doc/latest/guide/conf.html#config

FOUND THIS USEFUL? SHARE IT

comments (1 “Application configurations setting in Grails 3”)

  1. pramod

    Hi,

    Can you please let me know, how to pickup the properties set up on a WAS server and if you have any reference for deploying on WAS server can you please help me out with that ?

    Thanks in advance
    Pramod

    Reply

Leave a comment -