Declarative Replacement of Annotation-Driven Bean Definitions in Spring

11 April 2010

If you are using Spring 3 and configure your dependencies explicitly in a @Configuration class, it's fairly easy to replace one dependency with another. All you need to do is declare two dependencies with the same bean name in two separate config classes. The beans of the config which is registered last to the ApplicationContext, will simply override the beans defined in previously registered config classes.

Things get a bit more tricky, however, when you try to override a bean that has been wired up automatically using annotations. In this case, simply registering a config class that contains a bean with the same name as the annotated dependency doesn't yield the desired effect. It's very well possible that using a JavaConfigApplicationContext might solve the issue but while JavaConfig integration with the latest Spring 3 is flakey, this seems not an option. In the meantime, here's an example that demonstrates a solution to achieve the desired behaviour: