Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

decorating Spring beans provided by Grails

Tags:

spring

grails

I know that I can replace a Spring bean provided by Grails simply by defining my own bean with the same name. For example, if I want to replace the messageSource bean provided by Grails

class MyMessageSource implements MessageSource {
    // methods omitted
}

Then add the following in resources.groovy

messageSource(MyMessageSource)

However, assume that I want MyMessageSource to decorate the implementation of this bean provided by Grails

class MyMessageSource implements MessageSource {

    // this field should be set to the MessageSource impl provided by Grails
    MessageSource messageSource
}

I can't figure out how to wire this up in resources.groovy. Obviously I can't do this:

messageSource(MyMessageSource) {
    messageSource = ref('messageSource')
}

Because it looks like I'm defining a bean that depends on itself. I could of course give my bean a different name, e.g.

myMessageSource(MyMessageSource) {
    messageSource = ref('messageSource')
}

But then any class beyond my control (e.g. a plugin class) that declares a dependency on messageSource will be set to the bean provided by Grails rather than my decorator.

like image 352
Dónal Avatar asked Feb 14 '23 00:02

Dónal


1 Answers

After the context is initialized you can retrieve the messageSource bean, create an instance of your bean that delegates to the messageSource bean and then register your bean with the context under the name "messageSource" so when DI happens, your bean is the bean that will be used. In a plugin you should be able to do this in doWithApplicationContext (not doWithSpring).

like image 82
Jeff Scott Brown Avatar answered Feb 23 '23 21:02

Jeff Scott Brown