在实际项目中,往往需要针对 开发、测试、生产 等不同环境使用不同的配置。如果每次切换环境都手动修改 spring.profiles.active,不仅繁琐,也容易出错。若依推荐结合 Maven Profile 的方式,在打包阶段自动选择并替换对应的配置,从而实现环境隔离与无侵入切换。
这种方式的核心思路是:
通过 spring.profiles.active=@spring.profile@ 与 Maven 的 profile 机制联动,在打包时指定环境参数,由 Maven 自动完成配置注入。
一、在 pom.xml 中定义多环境配置
首先在项目的 pom.xml 中配置多个 profile,分别对应不同运行环境,并为每个环境定义独立的属性值。
XML
<profiles>
<profile>
<!-- 开发环境 -->
<id>dev</id>
<properties>
<spring.profile>dev</spring.profile>
<nacos.server.address>127.0.0.1:8848</nacos.server.address>
</properties>
<activation>
<!-- 默认激活 -->
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<!-- 测试环境 -->
<id>test</id>
<properties>
<spring.profile>test</spring.profile>
<nacos.server.address>120.120.120.120:8848</nacos.server.address>
</properties>
<activation>
<activeByDefault>false</activeByDefault>
</activation>
</profile>
<profile>
<!-- 生产环境 -->
<id>prod</id>
<properties>
<spring.profile>prod</spring.profile>
<nacos.server.address>http://ruoyi.vip:8848</nacos.server.address>
</properties>
<activation>
<activeByDefault>false</activeByDefault>
</activation>
</profile>
</profiles>
同时需要开启资源过滤功能,使 Maven 在打包时能够替换配置文件中的占位符:
XML
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
这样,Maven 在打包阶段就可以将配置文件中的变量替换为对应环境的实际值。
二、在配置文件中使用占位符
接下来修改 application.yml 或相关配置文件,将环境相关参数改为占位符形式:
XML
# Tomcat
server:
port: 9201
# Spring
spring:
application:
name: ruoyi-system
profiles:
# 当前激活环境(由 Maven 注入)
active: @spring.profile@
cloud:
nacos:
discovery:
# 服务注册地址
server-addr: @nacos.server.address@
config:
# 配置中心地址
server-addr: @nacos.server.address@
file-extension: yml
shared-configs:
- application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}
这里的 @spring.profile@ 和 @nacos.server.address@ 会在打包时,由 Maven 根据当前激活的 profile 自动替换。
三、通过 Maven Profile 进行打包
在完成以上配置后,即可通过 Maven 命令指定不同环境进行打包,而无需修改任何配置文件内容。
XML
# 开发环境
mvn clean package -P dev
# 测试环境
mvn clean package -Ptest
# 生产环境
mvn clean package -P prod
例如,使用 test 环境进行打包时,配置文件中的:
XML
@nacos.server.address@
会被自动替换为:
XML
120.120.120.120:8848
从而生成完全适配测试环境的可运行包。
四、这种方式的优势
通过 Maven Profile 区分环境配置,具有以下明显优势:
-
无需频繁修改配置文件,降低人为操作风险
-
打包阶段即可确定运行环境,更符合 CI/CD 流程
-
各环境配置清晰隔离,便于维护与扩展
-
与若依微服务、Nacos 等组件天然契合
总结
在若依项目中,结合 Maven Profile + Spring Profiles 是一种成熟且推荐的多环境配置管理方案。通过在 pom.xml 中统一维护环境变量,并在配置文件中使用占位符,可以实现"一次配置,多环境复用",既提升了开发效率,也增强了部署的规范性与安全性。
