核心是开启resource filtering:需在pom.xml中声明变量、设true指定资源目录,并用@xxx@替代${xxx}避免与spring boot冲突,再通过-pprod等命令显式激活profile实现多环境替换。

要让 Maven 在打包时自动把配置文件里的占位符(比如 @db.url@ 或 ${version})替换成真实值,核心是开启并正确配置 resource filtering,而不是单纯写个变量就生效。关键在三个环节:声明变量、标记资源目录为可过滤、确保占位符语法不冲突。
1. 开启 resource filtering 并指定目录
默认情况下,Maven 不会替换任何占位符。必须在 pom.xml 的 <build><resources></resources></build> 中显式启用:
- 用
<directory>src/main/resources</directory>指定要处理的资源路径 - 必须设置
<filtering>true</filtering>,否则所有${xxx}或@xxx@都原样保留 - 如果只希望处理部分文件(如仅
.properties),可加<includes></includes>限定范围
2. 提供可替换的变量值
占位符要能被识别,变量必须有来源。常见方式有三种:
-
内置属性:如
${project.version}、${maven.build.timestamp},无需额外定义 -
pom 中
:在 <properties></properties>块里直接写<db.url>jdbc:mysql://prod-db:3306/app</db.url> -
Profile 属性:在
<profiles></profiles>里按环境定义,例如prodprofile 中设<activatedproperties>prod</activatedproperties>
3. 避免占位符语法冲突(尤其 Spring Boot 项目)
Spring Boot 默认也解析 ${xxx},若 Maven 和 Spring 同时处理,容易出错或清空值。推荐做法是换用独立分隔符:
- 在
<resources></resources>内添加<delimiters><delimiter>@</delimiter></delimiters> - 把配置文件中的
${db.url}改成@db.url@ - 这样 Maven 只替换
@xxx@,Spring Boot 完全忽略,互不干扰 - 典型应用:在
application.properties中写spring.profiles.active=@activatedProperties@
4. 配合 Profile 实现多环境切换
单靠 filtering 只能换值,无法区分环境逻辑。需结合 Profile:
- 在
<profiles></profiles>中定义dev、test、prod,每个含对应<properties></properties> - 打包时用命令激活:
mvn clean package -Pprod - 确保该 profile 被选中后,其内部定义的属性才能注入构建上下文,供 filtering 使用
- 不要依赖
activeByDefault=true,它易被settings.xml覆盖,务必显式指定-P











