spring 如何在另一个bean存在或不存在情况下创建bean,但不引发异常

mgdq6dx1  于 2023-03-07  发布在  Spring
关注(0)|答案(1)|浏览(248)

我有如下所示自动配置

public class ConfigClass {

    //create a builder
    @Bean
    public Builder builder() {
        return new Builder();
    }

    //create a bean if SampleBean exists

    @Bean
    @ConditionalOnBean(SampleBean.class, Builder.class)
    public SomeClass someClass(@Qualifier("builder") Builder builder, SampleBean sampleBean) {
        builder.set(sampleBean);
        return builder.getSomeClass();
    }

    //create a bean if above doesn't create a bean
    @Bean
    @ConditionalOnBean(SomeClass.class)
    @ConditionalOnMissingBean("someClass")
    public SomeClass someClass1(@Qualifier("builder") Builder builder) {
        return builder.getSomeClass();
    }
}

我为SampleBean设置了自动配置

public class SampleBeanConfig{
    @Bean
    @ConditionalOnProperty("example.property")
    public SampleBean (){
        return new SampleBean();
    }
}

因此,我正在测试的是我想要创建SomeClass bean,无论SampleBean是否存在。我已经注解了属性“example.property“。但是Spring在ConfigClass中抛出bean未找到异常,即未找到SampleBean。

s5a0g9ez

s5a0g9ez1#

您的解决方案是将相同的 @ConditionalOnProperty 注解添加到 someClass bean中:

@Bean
@ConditionalOnClass(SampleBean.class)
@ConditionalOnProperty("example.property")
public SomeClass someClass(Builder builder, SampleBean sampleBean) {
    builder.set(sampleBean);
    return builder.getSomeClass();
}

@Bean
@ConditionalOnBean(SomeClass.class)
public SomeClass someClass1(Builder builder) {
    return builder.getSomeClass();
}

@Bean
@ConditionalOnProperty("example.property")
public SampleBean sampleBean() {
    return new SampleBean();
}

因此someClass将只与sampleBean沿着创建(因为它们具有相同的注解)
希望对你有帮助:)

相关问题