【发布时间】: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 处于活动状态时)
有没有办法做到这一点?
可能的解决方案:
-
将
@Profile({"!profile-a"})添加到AppConfig中getA方法的顶部。 -
添加 if 检查主机参数是否存在。
我不想做以上两个,因为我必须在多个地方进行更改。 (还有很多其他 bean,例如
A和其他参数,例如host)
谢谢
如果需要任何说明,请告诉我。
【问题讨论】:
-
为什么不创建自定义注释
-
最初,我希望将配置文件特定的 bean 放在一个单独的文件中。配置文件将以不同方式处理事件。 (比如说,它不会写入数据库,而是写入磁盘)
标签: java spring dependency-injection spring-bean spring-profiles