Loading...

Tuesday, March 12, 2013

Grails Goodness: Set Property Values of Spring Beans in resources.groovy

We can configure Spring beans using several methods in Grails. We can for example add them to grails-app/conf/spring/resources.xml using Spring's XML syntax. But we can also use a more Groovy way with grails-app/conf/spring/resources.groovy. We can use a DSL to define or configure Spring beans that we want to use in our Grails application. Grails uses BeanBuilder to parse the DSL and populate the Spring application context.

To define a bean we use the following syntax beanName(BeanClass). If we want to set a property value for the bean we use a closure and in the closure we set the property values. Let's first create a simple class we want to configure in the Spring application context:

// File: src/groovy/com/mrhaki/spring/Person.groovy
package com.mrhaki.spring

import groovy.transform.ToString

@ToString
class Person {
    String name
    Date birthDate
}

Next we configure the bean in resources.groovy:

// File: grails-app/conf/spring/resources.groovy
import com.mrhaki.spring.Person

beans = {

    mrhaki(Person) {
        name = 'mrhaki'
        birthDate = Date.parse('yyyy-MM-dd', '1973-7-9')
    }

}

There is also an alternative syntax using Groovy's support for named method arguments. In Groovy named arguments are all grouped into a Map object and passed as the first argument. The BeanBuilder DSL supports this feature. When we define a bean we can use named arguments for the property names and values, use the BeanClass argument and automatically this will be converted to Map and BeanClass type arguments.

// File: grails-app/conf/spring/resources.groovy
import com.mrhaki.spring.Person

beans = {

    // Using named arguments to set property values. The named arguments
    // can be grouped together, but don't have to. Groovy will automatically
    // group them together into a Map and makes it the first argument of 
    // the 'mrhaki() bean definition method'.
    mrhaki(name: 'mrhaki', Person, birthDate: Date.parse('yyyy-MM-dd', '1973-7-9'))

}

Written with Grails 2.2.1

2 comments:

Jeff Pogodzinski said...

In what programming situations would this be helpful?

Thank you!

Jeff.

Hubert Klein Ikkink said...

@Jeff: this is useful for defining extra Spring beans. It shows two different ways to achieve the same thing.

Post a Comment