gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:36:58 25 4
gpt4 key购买 nike

如果 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com