Unexpected @Bean Definition Behavior when Using Inheritance in @Configuration Classes #28137
Labels
in: core
Issues in core modules (aop, beans, core, context, expression)
status: duplicate
A duplicate of another issue
Affects: 5.3.16
The interaction of Spring @configuration annotated classes with @bean annotated method and inheritance behaves sort of like normal java inheritance and sort of like inclusion, but not consistently in either way.
For example if:
and given:
one would expect:
Expectations 1 and 2 are not met in that the bean defined by the parent class does exist in the context. And expectation 3 is only met if the names agree between the child and parent.
One could maybe argue that inheritance behaves like inclusion, which I would find weird, but a model, but then that is not consistent with itself, in that the value of the bean will be the result of the overridden method and not the parent method.
Other people have also been confused by this: https://stackoverflow.com/questions/39573558/spring-java-config-extending-an-abstract-configuration. The answers in that SO post are not really satisfying and amount to "well that's how it's implemented".
The following code reproduces the issue (also attached as a gradle project):
Running this program produces the following output:
Given normal inheritance rules and the rules for annotations on methods the expected output would be:
What spring gives us is actually:
Let's see if this is consistent with an inheritence == inclusion model by running some tests:
I believe the correct behavior, as outlined above, should be consistent with Java method annotation rules w/r/t inheritance.
I'm not exactly sure I see the exact fix, but it would seem that ConfigurationClassParser should do some checking of overridden @bean methods prior to adding them to the ConfigurationClass. Since they are recursively parsed, starting at the actually registered class, it should be possible to do a check for overloads prior to registering. Or maybe this is the wrong place altogether to do it.
At a minimum, I think that the documentation should be clarified about what the rules and effects are of inheritance in @configuration annotated classes.
spring-container-inheritance-bug.tar.gz
The text was updated successfully, but these errors were encountered: