Spring Profile - 如何包含 AND 条件以添加 2 个配置文件?

Pun*_*cky 6 java spring spring-boot

如果活动配置文件是测试的或本地的,我不希望加载特定的 bean。但是,当我设置以下时,spring 似乎将其视为“或”,并且该方法在活动配置文件是测试或本地时都会执行。但是,如果 remove say local 并保留 test ,则在配置文件为 test 时不会创建 bean。

@Profile({"!test","!local"})
Run Code Online (Sandbox Code Playgroud)

f-C*_*-CJ 5

从 Spring 5.1(包含在 Spring Boot 2.1 中)开始,可以在配置文件字符串注释中使用配置文件表达式。所以:

Spring 5.1 (Spring Boot 2.1) 及更高版本中,它很简单:

@Component
@Profile("!test & !local")
public class MyComponent {}
Run Code Online (Sandbox Code Playgroud)

弹簧 4.x 和 5.0.x

这个 Spring 版本有很多方法,每一种都有其优点和缺点。如果没有很多组合涵盖我个人比较喜欢使用的方法@Conditional类似@Stanislav回答类似的问题。为方便读者,我将解决方案贴在这里:

你的春天豆:

@Component
@Conditional(value = { NotTestNorLocalProfiles.class })
public class MyComponent {}
Run Code Online (Sandbox Code Playgroud)

NotTestNorLocalProfiles 执行:

public class NotTestNorLocalProfiles implements Condition {
    @Override
    public boolean matches(final ConditionContext context, final AnnotatedTypeMetadata metadata) {
        return !context.getEnvironment().acceptsProfiles("test")
                    && !context.getEnvironment().acceptsProfiles("local");
    }
}
Run Code Online (Sandbox Code Playgroud)

其他方法可以在这个类似的问题中找到:

当多个配置文件未处于活动状态时如何有条件地声明 Bean?

Spring:如何在 Profiles 中做 AND?


Com*_*ass 3

使用 Spring Boot 1.X 时,您可以使用附加配置文件名称更新系统属性,并处理SpringApplication.run. 如果符合条件,您可以将配置文件名称附加到活动配置文件中。如果没有,你就不会改变任何事情。

这是一个非常基本的检查,但您可以添加更严格的配置文件验证,例如空检查和实际拆分配置文件列表。

    String profile = System.getProperty("spring.profiles.active");
    if(!profile.contains("test") && !profile.contains("local")) {
        System.setProperty("spring.profiles.active", profile + ",notdev");
    }
Run Code Online (Sandbox Code Playgroud)

如果您使用的是 Spring Boot 2.0,则可以使用addAdditionalProfiles添加配置文件(没有 SB2 应用程序,所以我无法测试它,但我假设它只是将其添加到系统属性列表中)。

    String profile = System.getProperty("spring.profiles.active");
    if(!profile.contains("test") && !profile.contains("local")) {
        SpringApplication.addAdditionalProfiles("notdev");
    }
Run Code Online (Sandbox Code Playgroud)

那么你的注释可以是:

@Profile({"notdev"})
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

6272 次

最近记录:

7 年,3 月 前