java - Spring - 如果存在主 bean,则不要创建 bean

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

如果 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:(仅当 profile-a 处于 Activity 状态时才会创建这些 bean)

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

在此选择 profile-a 时,类型 a 的bean将来自 extile> extileconfig.java 。但问题是当 profile-a 处于 Activity 状态时,AppConfig.java 中的参数 host 不可用,因此 AppConfig 中的 getA 方法抛出异常.

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

有什么办法可以实现吗?

可能的解决方案:

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

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

    我不想执行以上两个操作,因为我必须在多个地方进行更改。 (还有一堆其他 bean,比如 A 和其他参数,比如 host)

谢谢

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

最佳答案

Condition annotationsSpring Boot auto-configuration是一种约束 bean 创建的解决方案。

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

示例:

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

关于java - Spring - 如果存在主 bean,则不要创建 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40541358/

相关文章:

java - Spring MVC错误通过字段表达的依赖关系不满足

java - 如何从链接获取完整视频下载?

java - Axon:如何为单个事件配置 amqp 发布?

java - Spring Batch MultiResourceItemReader - 仅用于组合文件?

java - 使用配置类时将@PreAuthorize 或@Secured 与 Jersey 一起使用

java - 如何最好地从 Spring WebClient 的 ClientResponse 中获取字节数组?

javascript - 构建 Javascript 模块

java - Android Google Drive 发送/创建文件

java - Android 4+ 操作栏选项卡在首次启动时显示为下拉列表 - 为了防止?

java - Spring DI NullPointerException @Autowired 失败