SpringBoot多环境配置
1、多环境配置
多环境实现是通过多套配置文件实现的,SpringBoot项目中多环境就是通过多个properties配置文件实现:SpringBoot通过application-xxx来支持多套环境配置,其中application.properties文件中保存公共的配置项,各个环境的配置项放在各自的配置文件中,如图所示

2、环境指定
方式一:直接在application.properties指定环境文件:spring.profiles.active=dev
方式二:配置环境变量,在打包或者启动项目时指定使用的环境名称
- 打包时传入变量值:mvn clean package -Denv=pro
- 测试时传入变量值:mvn clean test -Denv=pre
Maven的profile实现多套环境
1、多环境配置
在pom中使用profile来指定定义出不同的环境:
<profiles>
<profile>
<id>dev</id>
<properties>
<db.driver>com.mysql.jdbc.Driver</db.driver>
<db.url>jdbc:mysql://localhost:3306/test</db.url>
<db.username>admin</db.username>
<db.password>admin</db.password>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>pre</id>
<properties>
<db.driver>com.mysql.jdbc.Driver</db.driver>
<db.url>jdbc:mysql://localhost:3306/test_db</db.url>
<db.username>root</db.username>
<db.password>root</db.password>
</properties>
</profile>
<profile>
<id>pro</id>
<properties>
<db.driver>com.mysql.jdbc.Driver</db.driver>
<db.url>jdbc:mysql://localhost:3306/test_db</db.url>
<db.username>root</db.username>
<db.password>root</db.password>
</properties>
</profile>
</profiles>
2、多环境指定
方式一:使用默认配置
<activation>
<activeByDefault>true</activeByDefault>
</activation>
方式二:使用profiles指定环境
方式三:使用命令指定环境
打包命令:mvn clean package -P pro
SpringBoot结合Maven的profile实现多环境
1、多环境配置
多环境配置使用SpringBoot的application-xxx.properties实现环境配置;
2、使用profile标识配置环境
- id代表不同的配置环境
- 标签<env>是自定义,用来标识对应的环境文件
3、引用对应的环境
在application.properties中引用对饮的配置文件,通过引用自定义标签来实现
4、使用指定环境变量
参数-P指定的时profile的id,这时候环境变量使用的就是env对应的变量,properties里引用了env,所以就使用了env所标识的变量。
方式一:通过命令来指定对应环境变量:同Maven指定profile命令
mvn clean package -P env_pro
方式二:使用profiles来指定环境:同Maven指定profile命令