依赖于多个配置文件的Spring bean



我必须创建一个bean,这取决于两个可能的配置文件中的一个是否处于活动状态,或者如果这些配置文件都不处于活动状态,则创建一个不同的bean。我有以下内容:

@Profile("!A & !B")
@Bean(name = "myBean")
@Autowired
public Object myBean() {
...
}
@Profile({"A", "B"})
@Bean(name = "myBean")
@Autowired
public Object myBean() {
...
}

此代码仅在没有配置文件A或B处于活动状态时才有效。为了使它在A或B处于活动状态时工作,我必须切换bean声明的顺序。

我试着在不同的文件中声明bean,它似乎工作,但我不明白为什么不。

我也不明白为什么"!A & !B"符号似乎有效,但"A | B"不起作用,所以我必须在这种情况下使用{"A", "B"}

你能解释一下为什么把它们放在同一个文件中只适用于声明的第一个bean和所关注的符号吗?

感谢

您可以简单地用org.springframework.core.env.Profiles测试您的配置文件表达式。例如:

Set<String> activeProfiles = new HashSet<>();
activeProfiles.add("A");
activeProfiles.add("B");
System.out.println(Profiles.of("!A & !B").matches(activeProfiles::contains)); //false
System.out.println(Profiles.of("A", "B").matches(activeProfiles::contains)); // true

现在进入代码

1。

此代码仅在没有配置文件A或B处于活动状态时才有效

Set<String> activeProfiles = Collections.emptySet();
System.out.println(Profiles.of("!A & !B").matches(activeProfiles::contains)); // true
System.out.println(Profiles.of("A", "B").matches(activeProfiles::contains)); // false

第一个bean是活动的。

2。

要使它在A或B处于活动状态时工作,我必须切换bean声明的顺序

不,你不需要切换任何东西:

Set<String> activeProfiles = new HashSet<>();
activeProfiles.add("A");
System.out.println(Profiles.of("!A & !B").matches(activeProfiles::contains)); //false
System.out.println(Profiles.of("A", "B").matches(activeProfiles::contains)); // true

因此第二个bean将始终处于活动状态。

3。

"A | B"也没有任何问题,类似于"A", "B":

Set<String> activeProfiles = new HashSet<>();
activeProfiles.add("A");
System.out.println(Profiles.of("A | B").matches(activeProfiles::contains)); // true
System.out.println(Profiles.of("A", "B").matches(activeProfiles::contains)); // true

最新更新