maven中profiles使用详解,多环境开发配置文件(开发,测试,生产)+ pom中resources部分标签介绍
2025-04-03 10:08 ly772186472 阅读(687) 评论(0) 收藏 举报使用的场景
常常遇到一些项目中多环境切换的问题。比如在开发过程中用到开发环境,在测试中使用测试环境,在生产中用生产环境的情况。springboot中提供了 spring.profile.active的方式来实现多环境的切换,通过设置环境变量和启动参数的方式。但是这样做终究不能一劳永逸,要么需要修改yml文件,要么需要记得启动的时候带上参数。
而利用maven的profiles,可以减少很多工作。
1.pom.xml中添加
需要在pom.xml中添加以下配置xml配置
<profiles><!--步骤一:多环境配置,根据不同的环境将对应的环境变量设置到项目中-->
<profile><!-- 本地开发环境 --><!--不同环境Profile的唯一id-->
<id>dev</id>
<properties>
<profiles.active>dev</profiles.active>
</properties>
<!--配置默认的,配置文件,右侧的maven中,profiles默认选中dev-->
<activation>
<activeByDefault>
true
</activeByDefault>
</activation>
</profile>
<profile><!-- 联调环境 -->
<id>init</id>
<properties>
<profiles.active>init</profiles.active>
</properties>
</profile>
<profile><!-- 灰度环境 -->
<id>gray</id>
<properties>
<profiles.active>gray</profiles.active>
</properties>
</profile>
</profiles>

2.1.application.yml中代码如下
#多环境配置开发时使用-不放开则使用application.properties
spring.profiles.active=@profiles.active@
2.2. application-dev.yml中代码如下
server:port: 7091
2.3.maven打包与激活profiles
你可以执行命令
mvn clean package -Ptest
可以查看jar包中的配置文件变化,然后启动jar包,可以看到jar包启动的是test的配置,如果换成-Pdev启动的就是dev包的端口
默认启动方式
如果不带-Ptest,启动的是 1.pom.xml中添加 的环境 的因为在profiles中我们看到有配置默认的选项。
mvn clean package -Ptest
不推荐: settings.xml中使用activeProfiles指定
<activeProfiles> <activeProfile>profileTest1</activeProfile> </activeProfiles>
通过IDEA的可视化的方式
当然如果使用IDEA工具进行开发,还可以使用可视化的方式进行打包。

浙公网安备 33010602011771号