前提
使用多个环境的时候,一直想只需要修改profiles,然后运行即可生效的方法;网上查到的内容,有误导,也不全生效,这里将整理的记录一下.
总结
完整的多环境配置:
1.添加多个配置文件
2.application.yml 配置修改
3.pom.xml配置内容
4.pom.xml配置,(有两种方式,任选一种即可,不需要都配上)
5.项目启动前的build过程移交给maven(这点网上没查到)
其中前3步,哪里的文章都有,重点是后两步
1.添加多个配置文件
2.application.yml 配置修改
spring:
profiles:
default: '@env@'
3.pom.xml中配置<profiles>
<profiles>
<profile>
<id>test</id>
<properties>
<env>test</env>
</properties>
<activation>
<!-- 默认环境 -->
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>dev</id>
<properties>
<env>dev</env>
</properties>
</profile>
<profile>
<id>prod</id>
<properties>
<env>prod</env>
</properties>
</profile>
</profiles>
4.pom.xml配置
这里有两种方式,选一个即可,个人使用第一种,也推荐第一种:
- 配置spring-boot-maven-plugin组件;
- 配置<resources>
4.1配置spring-boot-maven-plugin组件
<build>
<!-- 设置jar打包时名称-->
<finalName>project-model</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<!-- version随springboot的版本,我这里如果不显式指定插件会飘红 -->
<version>2.7.3</version>
<configuration>
<fork>true</fork>
<!-- spring-boot:run 中文乱码解决 -->
<jvmArguments>-Dfile.encoding=UTF-8</jvmArguments>
<mainClass>com.gxl.life.web.ProjectModelApplication</mainClass>
</configuration>
</plugin>
</plugins>
</build>
插件的作用请自己动手
4.2 配置<resources>
注意如果使用了4.1的方式就跳过这里,并且我自身没有使用这种方式,也没有删除4.1的单独去验证,所以配置上可能有误;
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
<resource>
<directory>src/main/resources-env/${env}</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
5.build过程移交给maven
如果没有这一步,在每次切换环境后手动执行compile也可以运行;但是如果切换环境后直接运行就容易出错;
原因是直接运行前会先使用idea自身的build编译,此时不会替换配置文件中的@env@;
所以按下图设置,作用是将build过程移交给maven