1. 前言
为方便开发和统一管理,项目切换环境统一由IDEA的maven插件可视化修改,不提供命令行方式,有兴趣请自行探索
2. 在项目Pom文件project
标签下新增如下标签
<!--多环境部署 dev test prod -->
<profiles>
<profile>
<id>dev</id>
<properties>
<profileActive>dev</profileActive>
</properties>
<activation>
<!--指定默认激活-->
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>test</id>
<properties>
<profileActive>test</profileActive>
</properties>
</profile>
<profile>
<id>prod</id>
<properties>
<profileActive>prod</profileActive>
</properties>
</profile>
</profiles>
3. 修改配置文件
3.1 将不同环境的配置文件命名为application-{环境}文件
resources/
├── application-dev.yml
├── application-prod.yml
├── application-test.yml
└── application.yml
3.2 修改application.yml
# profileActive 为pom中properties标签声明的变量,如需修改记得同步修改,打包时会替换为变量标签里的值
spring:
profiles:
active: @profileActive@
3.3 修改maven引入的范围
<resources>
<resource>
<directory>src/main/resources</directory>
<!-- 开启过滤和参数替换 -->
<filtering>true</filtering>
<includes>
<!--读取打包命令中指定的环境-->
<include>application-${profileActive}.yml</include>
<include>application.yml</include>
<include>**/*.xml</include>
<include>templates/**</include>
</includes>
</resource>
</resources>