Wednesday, 11 January 2012

Extending Grails' beans with your own subclass

We've just completed a small Grails 2.0 plugin. One of the things this plugin does is to replace Grails' "groovyPageLocator" bean with our subclass implementation that changes the way the class behaves slightly. It was a little tricky to get my subclass injected with its dependencies also injected correctly, so I thought I'd write up a quick blog to document how we did it.

When it came to defining our bean, I basically wanted to override the groovyPageLocator, defined in "doWithSpring" in the GroovyPagesGrailsPlugin. I managed to do so by basically copying/pasting the bean definition and to change the bean class - but this seemed a nasty hack. If, in future Grails versions this plugin changes, we'd have to mirror the change in our, y'know, code duplication and all.

As the doWithSpring closure is just setting up the template for Spring to wire-up our beans, we can fiddle around with the beans here to achieve what we want.

In the end, here's the code we used to inject our own subclass in place of Grails' bean:

def doWithSpring = {
def pageLocator = delegate.getBeanDefinition("groovyPageLocator")
pageLocator.beanClass = PluginAwareGroovyPageLocator
pageLocator.propertyValues.add("order", "someValue")

So, we're just grabbing the existing bean from the definition, changing its class to point to my new class and adding in a custom property that's specific to my subclass. Lovely!

No comments: