Accessing Spring Beans by Implementing ApplicationContextAware in Grails Artefacts

20 / Nov / 2009 by Vivek Krishna 0 comments

Many a times, it is required to inject a Spring Bean into a Grails artefact. It has happened a few times with us in our projects that we needed to inject a TagLib bean in the service layer for code re-use for sending out e-mails. This is how we achieved it

MyService implements org.springframework.context.ApplicationContext

Import the classes import org.springframework.context.ApplicationContext and org.codehaus.groovy.grails.commons.ConfigurationHolder

Define a method as given below

public def getMyTag() {
return ConfigurationHolder.config.applicationContext.getBean(“MyTagLib”)

where MyTagLib is a TagLib class is a custom TagLib class. For ApplicationTagLib, which contains the tags like createLink() ,replace “MyTagLib” with “ApplicationTagLib” as the argument in the getBean() method.

We can access the methods/closures in the bean with a statement like myTag.methodName()

One thing to note is that writing something like

def myTag = ConfigurationHolder.config.applicationContext.getBean("MyTagLib")

will not work because applicationContext would not have been initialized then and an exception will be thrown.
Hope this Helps.

S Vivek Krishna


Leave a Reply

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