在一个项目中,我们经常会面对不同的运行环境,如本地环境、开发环境、测试环境、生产环境等,而在不同的环境中,数据源配置、日志文件配置、及一些软件运行过程中的基本配置可能都会不一致。这样使得每次在不同的环境里运行时都需要修改相应的配置文件,是个很麻烦的事情,所以需要给每个环境加入一个属于它的配置文件,切换环境时直接勾选编译即可,具体应该怎么操作呢?
1 为每个环境建立配置文件
在resources目录下建立env文件夹,再在其下建立local、dev、test、prod文件夹,每个文件夹下建立属于此环境的配置文件,如下图:
修改原application.yml文件内容为:
spring:
profiles:
active: @profile.active@
意为通过profile.active
来指定选用的配置文件。
2 修改maven的配置文件pom.xml
2.1 新建环境文件<profile>
<profiles>
<profile>
<!-- 本地环境 -->
<id>local</id>
<activation>
<!-- 默认激活此环境 -->
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<profile.active>local</profile.active>
</properties>
</profile>
<profile>
<!-- 开发环境 -->
<id>dev</id>
<properties>
<profile.active>dev</profile.active>
</properties>
</profile>
<profile>
<!-- 测试环境 -->
<id>test</id>
<properties>
<profile.active>test</profile.active>
</properties>
</profile>
<profile>
<!-- 生产环境 -->
<id>prod</id>
<properties>
<profile.active>prod</profile.active>
</properties>
</profile>
</profiles>
2.2 在<build>
中配置profile
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<!-- 使得application.yml里的标识符生效 -->
<filtering>true</filtering>
<excludes>
<!-- 资源根目录排除各环境的配置,后续使用单独的资源目录来指定 -->
<exclude>env/**</exclude>
</excludes>
</resource>
<resource>
<!-- 根据参数指定资源目录 -->
<directory>src/main/resources/env/${profile.active}</directory>
<targetPath>${project.build.outputDirectory}</targetPath>
<includes>
<include>**/*</include>
</includes>
</resource>
</resources>
……
</build>
3. 编译/打包运行
上述操作完成后,默认采用了local
本地环境,如果想修改,可以在maven面板中进行勾选。
评论区