Skip to main content

Development

Grails: How to configure additional beans

As you may know, Grails is actually a Spring MVC application in disguise.  Meanwhile dependency injection is the key point of Spring. Thus a quite natural problem for newcomers to Grails is that: how to configure more beans? Actually it’s as easy as in Spring.

Static Configuration:

  1. Using XML:

Beans can be configured using the “grails-ap/conf/spring/resources.xml” file of your applications using the same syntax as Spring. E.g.

<bean id=”myBean” class=”my.company.MyBeanImpl”></bean>

  1. Using the Spring DSL:

Define in “grails-app/conf/spring/resources.groovy”(create it if it doesn’t exist) as below:

Beans = {

switch(Environment.current) {

case Environment.PRODUCTION:

myBean(my.company.MyBeanImpl) {

bookService = ref(“bookService”)

}

break

case Environment.DEVELOPMENT:

myBean(my.company.mock.MockImpl) {

bookService = ref(“bookService”)

}

break

}

As you may notice, the biggest advantage of this way is you can mix logic in within your bean definitions (have different configuration under different environment in this example)

Runtime Configuration:

Normal cases:  use a “grails.spring.BeanBuilder” class that use dynamic Groovy to construct beans. E.g.

Def bb = new grails.spring.BeanBuilder()

bb.beans {

dataSource(BasicDataSource) {

driverClassName = “org.hsqldb.jdbcDriver”

url = “jdbc:hsqldb:mem:graislDB”

}

}

Within plug-ins, you don’t need to instantiate a BeanBuilder.  Instead the DSL is defined inside the “doWithSpring”.

Some explanation about BeanBuilder DSL:

Novices may get confused about this syntax (me too when I get first contact with Grails!) Actually it’s often used in Grails and not so much complex.

Suppose we have a bean class as follow:

MyExampleBean(String foo,int bar)

We can instantiate a bean as:

exampleBean(MyExampleBean, “stringArgument”,2)  { … }

where “exampleBean” is the bean variable name and “MyExampleBean” is the bean class name. “stringArgument” is assigned to foo, 2 is assigned to bar.

 

It’s quite simple, right?  Of course, you can visit “Grails and Spring” chapter of Grails doc for more details.

 

Useful links:

“Grails and Spring” chapter: http://grails.org/doc/latest/guide/spring.html

Groovy doc: http://groovy.codehaus.org/User+Guide

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Minjun Wang

More from this Author

Categories
Follow Us