【问题标题】:How to force spring to have exactly one active profile?如何强制弹簧只有一个活动配置文件?
【发布时间】:2021-10-03 08:15:11
【问题描述】:

我正在尝试在我的 SpringBoot 应用程序上激活一个,恰好一个配置文件。我曾经覆盖configureProfiles 方法,因此如果有多个配置文件处于活动状态,则应用程序不会运行。如果没有配置文件处于活动状态,我添加了一个默认配置文件。我想要激活的配置文件必须使用SPRING_PROFILES_ACTIVE 环境变量来定义。

在 SpringBoot 的最新版本 (2.5.x) 中,configureProfiles 是空的,并且在调用时,使用 SPRING_PROFILES_ACTIVE 定义的活动配置文件甚至不会加载。

知道如何在 SpringBoot 上拥有一个(不多也不少)活动的配置文件?

【问题讨论】:

    标签: java spring spring-boot spring-2.5


    【解决方案1】:

    SPRING_PROFILES_ACTIVE 环境变量将实际设置活动配置文件。

    如果您想获得活动配置文件,只需将 Environment 添加到您的 @SpringBootApplication 类并引发任何类型的 Exception 或在设置了多个配置文件的情况下关闭应用程序。

    请看下面一个简单的实现。

    import javax.annotation.PostConstruct;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.ApplicationContext;
    import org.springframework.core.env.Environment;
    
    @SpringBootApplication
    public class SpringDemoApplication {
    
        private Environment environment;
    
        public static void main(String[] args) {
            SpringApplication.run(SpringDemoApplication.class, args);
        }
    
        public SpringDemoApplication(Environment environment) {
            this.environment = environment;
        }
    
        @PostConstruct
        private void post() {
            if (!this.isThereJustOneActiveProfile()) {
                throw new RuntimeException("You must set just one profile.");
            }
        }
    
        private boolean isThereJustOneActiveProfile() {
            return (this.environment.getActiveProfiles().length == 1);
        }
    }
    

    【讨论】:

    • 你也可以使用@Autowired注入环境,不需要setter。
    【解决方案2】:

    您是否尝试过设置活动配置文件?

    private ConfigurableEnvironment env;
    ...
    env.setActiveProfiles(SPRING_PROFILES_ACTIVE);
    

    有很多方法可以设置您的个人资料。

    您可以查看:this Spring profiles tutorial

    或者这个post

    【讨论】:

      猜你喜欢
      • 2016-12-25
      • 2014-10-14
      • 2016-12-09
      • 2018-11-18
      • 2017-09-24
      • 1970-01-01
      • 1970-01-01
      • 2017-03-30
      • 1970-01-01
      相关资源
      最近更新 更多