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