引言
Spring Boot 的Profile配置,可以极大简化配置难度,可以有多种配置形式,根据位置有不同的生效方式。
探讨问题
Spring Boot 的 Profile 配置是为了解决不同环境可能存在的多种配置问题。
举例来说明的话,就是当我们开发完程序,部署到 测试环境或者生产环境的时候,可能需要配置不同的数据库连接,或者不同的日志打印级别。
通过Spring Boot的Profile 配置方式,可以方便地配置不同的配置信息,而且默认的情况也会顾及到,使用命令行也可以覆盖生效。非常方便。
获取当前生效的profile
如果希望在某个类中获取到当前生效的profile,可以通过 IOC 容器来获得。
@Autowired
private ApplicationContext context;
spring 的IOC 容器可以通过自动注入的方式获取到,通过 这个context,我们可以获得一个profile 数组,注意,这个数组可能等于 0 ,这代表没有任何 profile 生效。
String[] activeProfiles = context.getEnvironment().getActiveProfiles();// 检查 profile 是否正确
if (activeProfiles.length == 0) {System.out.println("未启用profile,非测试或开发环境!");return;
}
System.out.println("当前数据库连接环境:" + activeProfiles[0]);