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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With