Overriding properties in a Spring Bean with BeanFactoryPostProcessor
I was going through the source code of one of the Grails Plugins where I found the use of Spring’s BeanDefinitionRegistryPostProcessor to override some configurations that are available in DataSource.groovy. That involved a complete over riding of a PropertyValue definition.
It set me thinking about whether there is a way to override bean properties like String, Integer etc in a simpler way after the bean has initialized. In comes BeanFactoryPostProcessor, which provides a wonderful hook to do just that.
I created a small grails project and added a class CustomBean which looked like this :
[java]
class CustomBean {
String customVariable
}
[/java]
I registered a customBean on resources.groovy using
[java]
beans = {
customBean(CustomBean) {
String value = "Test Data From resources.groovy"
println "Setting value ${value}"
customVariable = value
}
customBeanPostProcessor(CustomBeanPostprocessor)
}
[/java]
This sets the initial value of customVariable as “Test Data From resources.groovy”.
If you are wondering what the customBeanPostprocessor is, that is just what I am going to explain next.
The bean implements the BeanFactoryPostProcessor interface and overrides the methods which provides us with hooks to modify the properties of the bean.
The class definition is:
[java]
import groovy.util.logging.Log4j
import org.springframework.beans.factory.config.BeanPostProcessor
@Log4j
class CustomBeanPostprocessor implements BeanPostProcessor{
@Override
Object postProcessBeforeInitialization(Object bean, String beanName) {
return bean
}
@Override
Object postProcessAfterInitialization(Object bean, String beanName) {
if(beanName == ‘customBean’) {
log.debug("Setting custom value inside post processor")
bean.customVariable = "Set from Post Processor"
}
return bean
}
}
[/java]
What amazed me is the elegance with which the developers of the framework has provided entry points into its internals without forcing the users to shave the yak.