【问题标题】:Spring - Don't create bean if a primary bean is presentSpring - 如果存在主 bean,则不要创建 bean
【发布时间】:2016-11-11 04:56:49
【问题描述】:

如果可以将 A 类型的 bean 作为主 bean 生成,是否可以阻止它的创建

示例:

我有两个配置类和两个配置文件。

AppConfig.java:(具有所有 bean 的通用配置类)

@Configuration
public class AppConfig {
    @Value("${host}")
    private String host;

    @Bean
    public A getA() {
        //uses the 'host' value to create an object  of type A
       // Involves database connections
    }
     
    @Bean
    public B getB(A a) {  //Others using bean A. This might come from either getA() or getOtherA()
        ...
    }

}

SpecificConfig.java:(这些 bean 只有在 profile-a 处于活动状态时才会创建)

@Configuration
@Profile("profile-a")
public class SpecificConfig{
    @Bean
    @Primary
    public A getOtherA() {
     //return a bean of type A
    }
}

这里选择profile-a 时,A 类型的bean 将来自SpecificConfig.java。但问题是当 profile-a 处于活动状态时,AppConfig.java 中的参数 host 不可用,因此 AppConfig 中的 getA 方法会引发异常。

由于类型 A 的 bean 已经存在或将存在(我不确定 bean 创建的顺序),我不希望 AppConfig 中的 getA() 被执行。 (当 profile-a 处于活动状态时)

有没有办法做到这一点?

可能的解决方案:

  1. @Profile({"!profile-a"})添加到AppConfiggetA方法的顶部。

  2. 添加 if 检查主机参数是否存在。

    我不想做以上两个,因为我必须在多个地方进行更改。 (还有很多其他 bean,例如 A 和其他参数,例如 host

谢谢

如果需要任何说明,请告诉我。

【问题讨论】:

  • 为什么不创建自定义注释
  • 最初,我希望将配置文件特定的 bean 放在一个单独的文件中。配置文件将以不同方式处理事件。 (比如说,它不会写入数据库,而是写入磁盘)

标签: java spring dependency-injection spring-bean spring-profiles


【解决方案1】:

Spring Boot auto-configurationCondition annotations 是一种限制 bean 创建的解决方案。

  • @ConditionalOnBean :检查指定的 bean 类和/或名称是否已包含在 BeanFactory 中。
  • @ConditionalOnProperty : 检查指定属性是否有特定值

例子:

@Configuration
public class SpecificConfig{
   @Bean
   @ConditionalOnBean(A.class)
   @Primary
   public A getOtherA() {
    //return a bean of type A
   }
}

【讨论】:

    猜你喜欢
    • 2011-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-24
    • 2017-07-22
    • 2018-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多