我正在尝试在我的SpringBoot应用程序上有一个,恰好是一个活动的配置文件。我过去常常覆盖configureProfiles方法,所以如果有多个配置文件处于活动状态,应用程序就不会运行。如果没有配置文件处于活动状态,我添加了一个默认配置文件。我想要激活的配置文件必须使用SPRING_PROFILES_ACTIVE环境变量来定义。
对于最新版本(2.5.x)的SpringBoot,configureProfiles是空的,当调用时,使用SPRING_PROFILES_ACTIVE定义的活动配置文件甚至不会被加载。
你知道我怎么才能在SpringBoot上有一个(不多也不少)活跃的个人资料吗?
发布于 2021-07-28 01:36:04
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);
}
}发布于 2021-07-27 21:46:38
您是否已尝试设置活动配置文件?
private ConfigurableEnvironment env;
...
env.setActiveProfiles(SPRING_PROFILES_ACTIVE);有很多方法可以设置你的个人资料。
你可以查看:this Spring profiles tutorial
或者这个post
https://stackoverflow.com/questions/68545981
复制相似问题