Maven 资源过滤(Resource Filtering)是 Maven 提供的一种机制,允许在构建过程中动态替换资源文件中的变量。这个功能对于管理不同环境的配置非常有用。
资源过滤的基本原理:
Maven 在构建过程中会扫描资源文件(如 properties、xml、yml 文件),将其中包含的 ${variable} 形式的变量替换为 POM 文件中定义的属性值。
配置资源过滤:
- 在 POM 中启用资源过滤:
xml<build> <resources> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> </resource> </resources> </build>
- 定义属性变量:
xml<properties> <database.url>jdbc:mysql://localhost:3306/mydb</database.url> <database.username>root</database.username> <database.password>password</database.password> <app.version>1.0.0</app.version> </properties>
- 在资源文件中使用变量:
properties# application.properties database.url=${database.url} database.username=${database.username} database.password=${database.password} app.version=${app.version}
结合 Profile 使用资源过滤:
xml<profiles> <profile> <id>dev</id> <properties> <env>dev</env> <database.url>jdbc:mysql://dev-db:3306/mydb</database.url> </properties> </profile> <profile> <id>prod</id> <properties> <env>prod</env> <database.url>jdbc:mysql://prod-db:3306/mydb</database.url> </properties> </profile> </profiles>
资源过滤的高级用法:
- 多资源目录配置:
xml<build> <resources> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> </resource> <resource> <directory>src/main/static</directory> <filtering>false</filtering> </resource> </resources> </build>
- 使用外部属性文件:
xml<build> <filters> <filter>src/main/filters/${env}.properties</filter> </filters> <resources> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> </resource> </resources> </build>
- 测试资源过滤:
xml<build> <testResources> <testResource> <directory>src/test/resources</directory> <filtering>true</filtering> </testResource> </testResources> </build>
注意事项:
- 资源过滤会增加构建时间,只对需要的文件启用过滤
- 避免在二进制文件(如图片、jar 包)上启用过滤
- 使用 Profile 区分不同环境的配置
- 敏感信息(如密码)应该使用环境变量或加密存储
- 在 CI/CD 流程中使用
-D参数传递动态属性
最佳实践:
- 使用
@variable@或${variable}格式,避免与 Spring 等框架的占位符冲突 - 在父 POM 中统一管理资源过滤配置
- 使用 Maven 的默认分隔符
${},也可以自定义分隔符 - 定期检查过滤后的文件,确保变量替换正确
资源过滤是 Maven 管理多环境配置的重要手段,能够显著简化配置管理工作。