A Grails application uses Spring under the hood, which means we can also use all of Spring's features in a Grails application. For example we can use the Spring Java configuration feature with our Grails application. The Java configuration feature allows us to write a Java or Groovy class to define beans for our application. Of course in Grails we have the nice bean builder syntax when we define beans in the grails-app/conf/spring/resources.groovy file, but maybe we must include a Java configuration from an external library or we just want to write a configuration class ourselves.

This post is very much inspired by this blog post by Andres Steingress.

First we create a simple Groovy class that we want to be instantiated via our Java configuration class:

// File: src/groovy/com/mrhaki/grails/Sample.groovy
package com.mrhaki.grails

class Sample {

    final String name

    Sample(final String name) {
        this.name = name
    }

}

Next we create a new Groovy class and apply the @Configuration annotation so Spring knows this is a class that is used to define beans. Inside the class we define public methods annotated with the @Bean annotation. By default the name of the method is also the name of the bean in the application context. We can specify a different name as an attribute of the @Bean annotation. We can inject other beans into our configuration class, for example GrailsApplication to access the configuration of our application.

// File: src/groovy/com/mrhaki/grails/BeansConfiguration.groovy
package com.mrhaki.grails

import org.codehaus.groovy.grails.commons.GrailsApplication
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration

@Configuration
class BeansConfiguration {

    // We can inject other Spring beans in our
    // configuration class. By default wiring
    // is done by type, so if we specify a type
    // it works.
    @Autowired
    GrailsApplication grailsApplication

    // If we want to wire by name we can use the
    // @Qualifier annotation:
    // @Autowired
    // @Qualifier('grailsApplication')
    // def grailsApplication

    @Bean
    Sample sample() {
        new Sample(grailsApplication.config.app.sample)
    }

}

The last step is to make sure our configuration class is picked up by Spring so the sample bean is configured. We use the Grails configuration property grails.spring.bean.packages to indicate the package our configuration class is in. When Grails starts all classes in the package and sub-packages are scanned to see if they are Spring components.

// File: grails-app/conf/Config.groovy
...
// packages to include in Spring bean scanning
grails.spring.bean.packages = ['com.mrhaki.grails']
...
// Set sample configuration property,
// which is used in BeansConfiguration.
app.sample = 'Grails is gr8!'
...

Code written with Grails 2.4.2.

Original article

shadow-left