Description
Eric Sirianni opened SPR-7341 and commented
The ConfigurationClassBeanDefinitionReader hardcodes the behavior that bean definitions from XML always override bean definitions from JavaConfig classes:
// has this already been overridden (e.g. via XML)?
if (this.registry.containsBeanDefinition(beanName)) {
BeanDefinition existingBeanDef = registry.getBeanDefinition(beanName);
// is the existing bean definition one that was created from a configuration class?
if (!(existingBeanDef instanceof ConfigurationClassBeanDefinition)) {
// no -> then it's an external override, probably XML
// overriding is legal, return immediately
if (logger.isDebugEnabled()) {
logger.debug(String.format("Skipping loading bean definition for %s: a definition for bean " +
"'%s' already exists. This is likely due to an override in XML.", method, beanName));
}
return;
}
}
I don't see why this decision was made. The normal semantics of using the order in which bean definitions were registered would seem to make sense to apply here as well.
For example:
@Configuration
@ImportResource("foo.xml")
class FooConfig {
@Bean bean1() { ... }
}
@Configuration
@ImportResource("bar.xml")
class BarConfig {
@Bean bean1() { ... }
@Bean bean2() { ... }
}
...
new AnnotationConfigApplicationContext(FooConfig.class, BarConfig.class)
I would expect the following override order to apply:
- beans defined in foo.xml
- overridden by beans defined in FooConfig
- overridden by beans defined in bar.xml
- overridden by beans defined in BarConfig
Instead it appears the override order is:
- beans defined in FooConfig
- overridden by beans defined in BarConfig
- overridden by beans defined in foo.xml
- overridden by beans defined in bar.xml
This is not intuitive. Specifically, note the interleaving of beans between both Foo and Bar configurations. The clients who use FooConfig and BarConfig don't care whether the beans defined by those Configuration classes come from XML or java. Yet, the override ordering forces them to be aware of this implementation detail.
I realize changing the behavior outright might present a backwards compatibility issue, so is it possible to add a boolean option to the ApplicationContext to respect the registration ordering regardless of whether the bean definition comes from XML or JavaConfig?
Affects: 3.0.3
Issue Links:
- Revised support for bean definition visibility and overriding [SPR-8189] #12839 Revised support for bean definition visibility and overriding ("is depended on by")
- Allow @Bean methods to override definitions in XML [SPR-7028] #11690 Allow
@Bean
methods to override definitions in XML
24 votes, 21 watchers