maven profile 通过激活注入 properties,变量替换实际发生在资源过滤阶段;需显式激活 profile、配置 filtering 并设置 delimiters 避免与 spring boot 冲突,再用 @activatedproperties@ 动态写入 spring.profiles.active。

Maven 的 Profile 机制本身不直接“替换 pom 中的变量”,而是通过激活特定 profile,将其中定义的 <properties></properties> 注入构建上下文,供资源过滤、插件配置等环节使用。真正发生变量替换的阶段是 资源过滤(resources filtering),不是 pom 解析本身。
确保 profile 被正确识别和激活
在 pom.xml 的 <profiles></profiles> 中定义环境 profile,并显式指定 ID:
- 每个
<profile></profile>必须有唯一<id></id>,如dev、test、prod - 避免依赖
activeByDefault=true—— 它容易被settings.xml中同名 profile 静默覆盖 - 打包时必须用命令显式激活:
mvn clean package -Pprod
让变量在配置文件中生效:开启 filtering 并配对路径
仅定义 <properties></properties> 不会自动改配置文件。需配合 maven-resources-plugin 的 filtering 功能:
Java JDK 25 来自 OpenJDK 官方归档,版本为 JDK 25,本条下载地址已指向官方 Windows x64 zip 安装包直链,适合调试旧项目或兼容旧版 Java 运行环境。
- 在
<build><resources></resources></build>中声明要处理的目录(通常是src/main/resources) - 设置
<filtering>true</filtering>,否则占位符原样保留 - 确保待替换的文件(如
application.properties)位于该<directory></directory>下 - 示例:
<resource><br><directory>src/main/resources</directory><br><filtering>true</filtering><br></resource>
避免 Maven 和 Spring Boot 双重解析冲突
两者默认都识别 ${xxx},易导致占位符被清空或二次解析失败。最稳妥做法是换一套占位符语法:
- 在
<build><resources></resources></build>内添加<delimiters><delimiter>@</delimiter></delimiters> - 把配置文件中的
${db.url}改成@db.url@ - Maven 只替换
@xxx@,Spring Boot 默认完全忽略,互不干扰
把环境标识写进 Spring Boot 的 profiles.active
让应用启动时自动加载对应环境配置(如 application-prod.yml):
- 在
src/main/resources/application.properties中写:spring.profiles.active=@activatedProperties@ - 在 profile 中定义对应属性,例如:
<profile><br><id>prod</id><br><properties><br><activatedproperties>prod</activatedproperties><br></properties><br></profile>
- 这样打包后,jar 中的
application.properties就会变成:spring.profiles.active=prod
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










