Spring Profile - 如何包含AND条件以添加2个配置文件? [英] Spring Profile - How to include AND condition for adding 2 profiles?

查看:484
本文介绍了Spring Profile - 如何包含AND条件以添加2个配置文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果活动配置文件是test或local,我不希望加载特定的bean。但是当我设置下面的内容时,spring似乎处理为或,并且当活动配置文件为test或local时,该方法都会被执行。但是,如果删除说本地并继续测试,那么在配置文件测试时不会创建bean。

I don't want a specific bean to be loaded if either the active profile is test or local. However when I set the below , spring seems to be treating is as "or" and the method gets executed both when active profile is test or local. However if remove say local and keep test , then the bean is not created when the profile is test.

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


推荐答案

使用Spring Boot 1.X时,您可以使用其他配置文件名称更新系统属性并处理所有 SpringApplication.run 之前的布尔逻辑。如果符合条件,则会将配置文件名称附加到活动配置文件。如果没有,你就不会改变任何东西。

When using Spring Boot 1.X, you can update the System Property with an additional profile name and handle all the boolean logic before your SpringApplication.run. If it qualifies, you would append the profile name to the active profiles. If it doesn't, you would not change anything.

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

This is a very basic check but you can add more rigorous profile validation, such as null check and actually splitting the profiles list.

    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应用程序,因此我无法对此进行测试,但我认为它只是将其添加到系统属性列表中)。

If you are using Spring Boot 2.0, you can use addAdditionalProfiles to add the profile (don't have a SB2 app so I can't test this but I assume it just adds it to the System properties list).

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

然后你的注释可以是:

@Profile({"notdev"})

这篇关于Spring Profile - 如何包含AND条件以添加2个配置文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆