了解自动配置和依赖注入期间 Bean 工厂行为为何存在差异
考虑以下配置类,它声明了两个 bean,bean B
只能在 bean A
的条件下创建。
@Configuration(
proxyBeanMethods = false
)
@AutoConfigureBefore(SomeOtherCOnfig.class)
@ConditionalOnProperty(name = "prop",havingValue = "false")
public class SomeConfiguration {
@Bean("beanA")
BeanA beanA() {
if (someCOndition){
return null;
}
return new BeanA();
}
@ConditionalOnBean(name = "beanA")
@Bean(name = "beanB")
BeanB beanB(@Qualifier("beanA") BeanA beanA) {
return new BeanB(beanA);
}
当 someCondition
为 true 时,我希望 beanA
在自动配置报告中不匹配,因此意味着永远不会尝试执行 beanB 创建。 我看到的行为是, beanA
被认为是自动配置中的正匹配
SomeConfiguration#beanB 匹配:- @ConditionalOnBean (names: beanA; SearchStrategy: all) found bean 'beanA' (OnBeanCondition)
尝试创建 和 beanB
,正如我所期望的那样,抛出了异常 引起:org.springframework.beans.factory.NoSuchBeanDefinitionException:没有合格的 bean of type
为什么在自动配置期间 beanA
被认为位于 beanFactory 中,但也不在那里什么时候注入依赖?
是因为 bean 存在,还是至少有一个指向 null null 的类型的引用?但如果是这种情况,spring 不应该向 beanB 注入一个 null bean
Considering the following configuration class which declares two beans, bean B
which should only be created on conditional of bean A
.
@Configuration(
proxyBeanMethods = false
)
@AutoConfigureBefore(SomeOtherCOnfig.class)
@ConditionalOnProperty(name = "prop",havingValue = "false")
public class SomeConfiguration {
@Bean("beanA")
BeanA beanA() {
if (someCOndition){
return null;
}
return new BeanA();
}
@ConditionalOnBean(name = "beanA")
@Bean(name = "beanB")
BeanB beanB(@Qualifier("beanA") BeanA beanA) {
return new BeanB(beanA);
}
When someCondition
is true I expect beanA
not to be matched in the autoconfiguration report thus mean beanB creation is never attempted to be executed.
The behaviour i see is, beanA
is considered a positive match in the autoconfiguration
SomeConfiguration#beanB matched:- @ConditionalOnBean (names: beanA; SearchStrategy: all) found bean 'beanA' (OnBeanCondition)
and beanB
is attempted to be created and as I expect happens the exception thrownCaused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type
Why is the beanA
considered to be in the beanFactory here during autoconfiguration but also not there either when injecting dependencies?
Is it because the bean is there, or at least a reference of type which points to null null? But if that is the case shouldn't spring be injecting a null bean to beanB
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论