September 22, 2015

Grails Goodness: Defining Spring Beans With doWithSpring Method

Grails 3 introduces GrailsAutoConfiguration as the base class for a Grails application. We can extend this class, add a main method and we are ready to go. By default this class is the Application class in the grails-app/init directory. We can override several Grails lifecycle methods from the GrailsAutoConfiguration base class. One of them is doWithSpring. This method must return a closure that can be used by the Grails BeanBuilder class to add Spring beans to the application context. The closure has the same syntax as what we already know for the grails-app/conf/spring/resources.groovy file, we know from previous Grails versions.

We start with a simple class we want to use as a Spring bean:

// File: src/main/groovy/com/mrhaki/grails/SampleBean.groovy
package com.mrhaki.grails

class SampleBean {
    String message

Next we create a class that implements the CommandLineRunner interface. Grails will pick up this class, if we configure it as a Spring bean, at startup and executes the code in the run method.

// File: src/main/groovy/com/mrhaki/grails/SamplePrinter.groovy
package com.mrhaki.grails

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.CommandLineRunner

class SamplePrinter implements CommandLineRunner {

    SampleBean sample

    void run(final String... args) throws Exception {
        println "Sample printer says: ${sample.message}"

Now we are ready to register these classes as Spring beans using the doWithSpring method in our Application class:

// File: grails-app/init/com/mrhaki/grails/Application.groovy
package com.mrhaki.grails

import grails.boot.GrailsApp
import grails.boot.config.GrailsAutoConfiguration

class Application extends GrailsAutoConfiguration {

    Closure doWithSpring() {
        // Define closure with Spring bean
        // definitions, like resources.groovy.
        def beans = {
            // Define Spring bean with name sample
            // of type SampleBean.
            sample(SampleBean) {
                message = 'Grails 3 is so gr8!'

            // Register CommandLineRunner implementation
            // as Spring bean.
        return beans

    static void main(String[] args) {
        GrailsApp.run(Application, args)


Now we can run our Grails application and in our console we see the message:

grails> run-app
| Running application...
Sample printer says: Grails 3 is so gr8!
Grails application running at http://localhost:8080 in environment: development

Written with Grails 3.0.7.