1.springboot多环境设置切换
1.通过多个properties|yaml文件;
默认会读取application.properties文件
多个:
1.分别创建对应的配置文件
application-环境名.properties|.yml
application-pro.properties |.yml正式
application-dev.properties|.yml开发
application-test.properties|.yml 测试
2.选择某一具体环境,在主配置中添加
properties: spring.profies.active=环境名
yml方式:
spring:
profiles:
active: pro
如果将application.properties文件注释掉,
sprinboot仍然会读取其他的application-环境名.properties中的配置;
且properties文件的优先级高于yml文件;
2.通过单个yaml文件 ;
#第一个环境(主环境)
server:
port: 9999
spring:
profiles:
active: dev #指定使用哪个环境
--- #使用 --- 来作为分隔符
#第二个环境(开发环境)
server:
port: 8001
spring:
profiles: dev
---
#第三个环境(测试环境)
server:
port: 8002
spring:
profiles: test
---
3.利用maven方式实现多环境的切换
1.在maven中使用profiles标签;
<!--配置信息-->
<profiles>
<!--开发环境-->
<profile>
<!--环境标识-->
<id>dev</id>
<activation>
<!--默认环境-->
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<spring.profiles.active>dev</spring.profiles.active>
<server.online.port>8082</server.online.port>
<server.eureka.port>8085</server.eureka.port>
<server.account.port>5583</server.account.port>
<server.zuul.port>8888</server.zuul.port>
<eureka.host>127.0.0.1</eureka.host>
<eureka.backup.one.port>9908</eureka.backup.one.port>
<eureka.backup.two.port>9909</eureka.backup.two.port>
<eureka.backup.three.port>9910</eureka.backup.three.port>
</properties>
</profile>
<!--测试环境-->
<profile>
<id>test</id>
<activation>
<activeByDefault>false</activeByDefault>
</activation>
<properties>
<spring.profiles.active>test</spring.profiles.active>
<server.port>8083</server.port>
</properties>
</profile>
<!--生产环境-->
<profile>
<id>pro</id>
<activation>
<activeByDefault>false</activeByDefault>
</activation>
<properties>
<spring.profiles.active>pro</spring.profiles.active>
<server.port>8084</server.port>
</properties>
</profile>
</profiles>
2.分别创建对应的配置文件
application-环境名.properties|.yml
application-pro.properties |.yml正式
application-dev.properties|.yml开发
application-test.properties|.yml 测试
3.在主配置文件中使用@spring.profiles.active@来引入;
spring.profiles.active=@spring.profiles.active@
使用maven方式配置文件的优先级:
1.properties和yml文件二者相互补充,可以集合使用,如果冲突,properties的优先级高于yml文件;
2.在maven中通过profile标签可以动态切换不同环境的配置信息,在properties或yml配置文件中
使用@@方式可以动态加载不同环境的配置信息;会指向<activeByDefault>true</activeByDefault>的环境的配置信息;
3.如果在maven的profile中的定义的信息和配置文件中冲突且沒有定义其对应的环境下的配置文件(application-${profile}.yml|properties),优先使用properties和yml文件中的配置信息;
4.在maven的profile中的定义的信息,如果指定了application-${profile}.yml|properties
优先使用指定的环境的配置信息;如果同时存在properties和yml文件properties的优先级高于yml文件;
4.动态切换环境;
1.通过运行参数指定环境(STS/Eclipse)run configration--> agruments(idea:run-edit configuration)
-- spring.profies.active=环境名 指定使用那个环境;
2.命令行模式
使用maven打包--> java -jar 项目名.jar --spring.profies.active=环境名
3.通过vm参数指定环境; run configration--> agruments-vm (idea:run-edit configuration)
-Dspring.profies.active=环境名