Spring Boot 多环境配置和切换
在开发过程中一个应用程序可能会在多个环境中运行,例如开发环境、测试环境、生产环境等,每一个环境的配置信息会分别保存到各自的配置文件中时,要如何配置及进行切换。
1.properties 多环境配置
使用properties 文件配置,需要多个application-xxx.properties 的文件,xxx为环境名,要选择某个环境需要一个主要的application.properties 配置spring.profiles.active=环境名。例如配置测试环境的文件application-dev.properties,与配置测试环境的文件application-test.properties的切换。
application-dev.properties文件中的配置:
server.port=8080
server.servlet.context-path=/
logging.level.com.qch.stringbootdemo=DEBUG
logging.level.org.springframework.boot=DEBUG
application-test.properties文件中的配置:
server.port=9090
server.servlet.context-path=/
logging.level.com.qch.stringbootdemo=DEBUG
logging.level.org.springframework.boot=DEBUG
配置完环境的配置文件后在主配置文件主需要配置spring.profiles.active=test将环境切换到测试环境,重新运行后观察控制台可以发现端口为选择的环境的端口。
2.yml 文件多环境配置
在yml 文件在配置多环境不需要多个配置文件,只需在一个yml文件中配置即可,每个环境之间使用‘- - -’隔开。
yml文件中的配置:
spring:
profiles:
active: dev #使用active指定使用的环境
---
server:
port: 8080
spring:
profiles: dev
---
server:
port: 9090
spring:
profiles: test