Registering new Spring beans in Grails during runtime

Sit down, son; This talk’s been a long-time comin’.
There may come a day when you find yourself having to register a new Spring bean during runtime of a Grails application.
I’m gonna show you a method that’s been passed down in our family for generations.

First, get hold of a reference to the GrailsApplication bean; You can’t register no new beans if you ain’t got access to the boss-man.

Then:

import org.springframework.beans.factory.support.GenericBeanDefinition
import org.springframework.beans.factory.config.ConstructorArgumentValues
import org.springframework.beans.factory.support.AbstractBeanDefinition
import org.springframework.beans.MutablePropertyValues

...

//Create a definition for the new bean
def beanDef = new GenericBeanDefinition(beanClass: NewBeanClass, 
    autowireMode: AbstractBeanDefinition.AUTOWIRE_BY_NAME)

//Provide the bean with any arguments required by the constructor
def argumentValues = new ConstructorArgumentValues()
argumentValues.addGenericArgumentValue('constructorArg1')
beanDef.setConstructorArgumentValues(argumentValues)

//Set additional properties such as references to other Spring beans
def propertyValues = new MutablePropertyValues()
propertyValues.add('booleanSwitch', true)
propertyValues.add('beanDependency1', 
    grailsApplication.mainContext.getBean(BeanDependency1))
beanDef.setPropertyValues(propertyValues)

//Register the new definition
grailsApplication.mainContext.registerBeanDefinition('newBeanClass', beanDef)

If y’all use some high-and-mighty IDE like Intellij IDEA, you may notice that the registerBeanDefinition method isn’t recognized by the mainContext.
This is because GrailsApplication exposes the main context with the interface of org.springframework.context.ApplicationContext, but it’s actually an instance of GrailsWebApplicationContext so this method is in fact accessible and it’s all legit.

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s