@Bean
@ConditionalOnBean(B.class)
public A a() {
return new A();
}
@Bean
//@ConditionalOnBean(A.class)
public B b() {
return new B();
}
The above code, only bean type named B can be loaded, the following code, bean type name A and bean type named B both be load.
@Bean
//@ConditionalOnBean(B.class)
public A a() {
return new A();
}
@Bean
@ConditionalOnBean(A.class)
public B b() {
return new B();
}
The writing order is different, and different effects are produced. Is it reasonable?
For the first demo code, should spring try to load B as much as possible when spring have scanned @ConditionalOnBean(B.class)?
Comment From: snicoll
The Javadoc of @ConditionalBean
has a note describing how it should be used. You must make sure the bean that is a target of the condition has been loaded before the condition applies.
In the future, please ask questions on StackOverflow: as mentioned in the guidelines for contributing, we prefer to use GitHub issues only for bugs and enhancements.
Comment From: bjmi
I recently had the same issue after splitting a big configuration class into two smaller ones.
Afterwards some beans weren't instantiated anymore that used @ConditionalOnBean
.
For me this is a bug too.
Otherwise @ConditionalOnBean
become useless and discouraged as the behaviour is unspecific.
See also: #7815