@Profile 注释中的 AND 运算符

Nuñ*_*ada 6 java spring spring-mvc spring-boot

我的 Spring Boot appl 中有这个配置类。v1.5.3. 发布

@Configuration
@Profile("dev && cub")
@PropertySource("file:///${user.home}/.cub/application-dev.properties")
public class CubDevelopmentConfig {
..
}
Run Code Online (Sandbox Code Playgroud)

这个属性在我的 application.properties 中定义

spring.profiles.active=dev, cub
Run Code Online (Sandbox Code Playgroud)

但未加载配置类

我也试过 @Profile("{dev && cub}")

dav*_*xxx 14

使用value()注解的方法的数组形式来指定多个值。
那是 : @Profile({"dev", "cub"})

然而,这种配置并不意味着“dev”和“cub”配置文件都是必需的。
其中至少一个的存在证实了该条件。

为了仅在两个配置文件都存在时启用配置,Spring Boot 到目前为止还没有提供开箱即用的解决方案。
从 Spring Core 5.1(Spring Boot 2.1 或更高版本)开始,您终于可以在@Profile. 注意不是 EL 而是有限的表达。

配置文件字符串可能包含简单的配置文件名称(例如"p1")或配置文件表达式。配置文件表达式允许表达更复杂的配置文件逻辑,例如"p1 & p2"。有关支持的格式的更多详细信息,请参阅 Profiles.of(String...)

根据javadoc,我们可以将多个配置文件的存在指定为条件:

@Profile("dev & cub")
Run Code Online (Sandbox Code Playgroud)

现在可以更明确地表达一个或另一个配置文件的存在:

@Profile("dev | cub")
Run Code Online (Sandbox Code Playgroud)

我们也可以依赖否定,例如:

@Profile("dev & !cub")
Run Code Online (Sandbox Code Playgroud)

请注意,&and|不能在不使用括号的情况下混合在同一个表达式中。所以它应该用作:

@Profile("(dev & integ) | cub")
Run Code Online (Sandbox Code Playgroud)

您可以在此处检索有关Profile表达式的所有规则。

作为一般注意事项,请注意配置文件的联合作为激活规则,因为这可能是由我们将“环境”耦合过多的糟糕设计引起的。