首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何强制弹簧恰好有一个活动轮廓?

如何强制弹簧恰好有一个活动轮廓?
EN

Stack Overflow用户
提问于 2021-07-27 21:40:03
回答 2查看 54关注 0票数 0

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

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

你知道我怎么才能在SpringBoot上有一个(不多也不少)活跃的个人资料吗?

EN

回答 2

Stack Overflow用户

发布于 2021-07-28 01:36:04

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

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

下面是一个简单的实现。

代码语言:javascript
复制
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);
    }
}
票数 1
EN

Stack Overflow用户

发布于 2021-07-27 21:46:38

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

代码语言:javascript
复制
private ConfigurableEnvironment env;
...
env.setActiveProfiles(SPRING_PROFILES_ACTIVE);

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

你可以查看:this Spring profiles tutorial

或者这个post

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68545981

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档