【问题标题】:Spring Profile - How to include AND condition for adding 2 profiles?Spring Profile - 如何包含添加 2 个配置文件的 AND 条件?
【发布时间】:2018-10-15 08:19:43
【问题描述】:

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

@Profile({"!test","!local"})

【问题讨论】:

标签: java spring spring-boot


【解决方案1】:

自 Spring 5.1(并入 Spring Boot 2.1)以来,可以在配置文件字符串注释中使用配置文件表达式。所以:

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

@Component
@Profile("!test & !local")
public class MyComponent {}

Spring 4.x 和 5.0.x

这个 Spring 版本有很多方法,每一种都有其优缺点。当没有太多组合可以涵盖时,我个人喜欢在类似问题中使用@Conditional 之类的@Stanislav answered 的方法。为了方便读者,我在这里发布解决方案:

你的 Spring Bean:

@Component
@Conditional(value = { NotTestNorLocalProfiles.class })
public class MyComponent {}

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");
    }
}

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

How to conditionally declare Bean when multiple profiles are not active?

Spring: How to do AND in Profiles?

【讨论】:

    【解决方案2】:

    使用 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");
        }
    

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

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

    那么你的注释可以是:

    @Profile({"notdev"})
    

    【讨论】:

      【解决方案3】:

      使用@Profile({"Dummy"})

      如果您想稍后使用有效的个人资料名称,您可以替换“Dummy”。

      【讨论】:

      • 谢谢@Sundarrajan。但我希望对其他配置文件执行此操作,例如 dev 、 qa 或我将来可能添加的任何其他内容。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-11
      • 1970-01-01
      • 2022-11-02
      • 2013-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多