了解自动配置和依赖注入期间 Bean 工厂行为为何存在差异

发布于 2025-01-14 22:43:54 字数 1117 浏览 5 评论 0原文

考虑以下配置类,它声明了两个 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 thrown
Caused 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文