本文来说下spring.profiles.active和spring.profiles.include的使用与区别
我们在开发Spring Boot应用时,通常同一套程序会被应用和安装到几个不同的环境,比如:开发、测试、生产等。其中每个环境的数据库地址、服务器端口等等配置都会不同,如果在为不同环境打包时都要频繁修改配置文件的话,那必将是个非常繁琐且容易发生错误的事。
对于多环境的配置,各种项目构建工具或是框架的基本思路是一致的,通过配置多份不同环境的配置文件,再通过打包命令指定需要打包的内容之后进行区分打包,Spring Boot也不例外,或者说更加简单。
一个好方法就是创建不同的配置文件,且命名规则遵循application-${profile}.yml,例如:
当然,我们不能删除项目最顶层的application.yml配置,在该文件中,根据部署场景不同,切换不同的配置文件:配置spring.profiles.active,属性值为${profile}。
在执行有参启动时,可以在命令中进行指定要选用的配置文件,例如:java -jar xx.jar --spring.profiles.active=test
这个命令的优先级是最高的,即使application.yml中已经配置spring.profiles.active=dev,最终程序还是会用application-test.yml配置文件。
再进一步,对于开发环境,想用不同的配置文件存储开发环境不同的配置,例如:
即在启用application-dev.yml开发环境(主)配置文件时,同时启用application-dev1.yml和application-dev2.yml。
那么,可以使用spring.profiles.include属性:同时启用其他的profile
若是properties文件:spring.profiles.include=dev1,dev2
若是yaml文件中,
spring.profiles.include:
-dev1
-dev2
或者:spring.profiles.include:dev1,dev2
配置区别
按照顺序,后面的覆盖前面的。
application.yml配置:
server:
port: 8088
#激活的是开发环境配置文件
spring:
profiles:
active: dev
application-dev.yml配置:
server:
port: 8089
#同时触发dev1和dev2的激活
spring:
profiles:
include: dev1,dev2
application-dev1.yml配置:
server:
port: 8090
application-dev2.yml配置:
server:
port: 8091
application-prod.yml配置:
server:
port: 9088
#同时触发prod1和prod2的激活
spring:
profiles:
include: prod1,prod2
application-prod1.yml配置:
server:
port: 9089
application-prod2.yml配置:
server:
port: 9090
在application.yml配置文件中,指定
#激活的是开发环境配置文件
spring:
profiles:
active: dev
启动时不指定参数
启动dev2中的8091端口
在测试一的基础上,启动时指定参数:–spring.profiles.active=prod。优先级最高,会使用生产环境配置文件
启动结果
在application.yml配置文件中,指定
#激活的是开发环境配置文件
spring:
profiles:
active: dev
include: dev1,dev2
启动结果
编写程序查看激活的yml文件
package com.wideth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
@Slf4j
@SpringBootApplication
public class AppApplication {
public static void main(String[] args) {
try {
ApplicationContext ctx = SpringApplication.run
(AppApplication.class, args);
String[] activeProfiles = ctx.getEnvironment().
getActiveProfiles();
for (String profile : activeProfiles) {
log.warn("Spring Boot 使用profile为:{}" , profile);
}
} catch (Exception e) {
log.error("启动失败!",e);
}
}
}
程序结果
本文介绍了spring.profiles的使用和相关的知识