Maven 3:如何在子模块中解析父POM的版本
解决方案:子模块解析父POM的${revision}版本号
针对你父POM中使用${revision}作为版本号,子模块需要获取该版本的场景,这里有几个经过验证的可行方案:
方案一:直接使用Maven内置属性引用
这是最直接省心的方式,只要子模块正确继承了父POM,就能通过Maven内置属性直接拿到父版本的实际值:
- 在子模块的POM、配置文件甚至构建脚本里,直接用
${project.parent.version}即可——它会自动解析父POM中${revision}最终生效的版本号。 - 注意前提:父POM里的
${revision}需要有明确的定义来源,你可以选这几种方式:- 在父POM的
<properties>块里显式声明:<properties> <revision>1.0.0-SNAPSHOT</revision> </properties> - 构建时通过命令行参数传递:
mvn clean install -Drevision=2.0.0 - 在
settings.xml的全局<properties>中配置默认值
- 在父POM的
举个实际用法例子,子模块里如果要依赖同版本的父项目组件:
<dependency> <groupId>com.test.test</groupId> <artifactId>shared-utils</artifactId> <version>${project.parent.version}</version> </dependency>
方案二:通过Maven Resources插件实现资源过滤
如果需要在子模块的配置文件(比如application.properties、config.yml这类业务配置)里用到父版本号,可以用资源过滤功能自动替换:
- 在子模块POM中开启资源过滤:
<build> <resources> <resource> <directory>src/main/resources</directory> <!-- 开启过滤,允许替换文件里的Maven属性占位符 --> <filtering>true</filtering> </resource> </resources> </build> - 在你的配置文件里用
${project.parent.version}当占位符:app.info.parent-version=${project.parent.version} - 执行
mvn clean package时,Maven会自动把占位符替换成父POM的实际版本号。
方案三:通过脚本扩展处理(进阶场景)
如果需要在构建过程中对父版本号做自定义逻辑处理(比如写入版本文件、传递给其他工具),可以用Maven Exec插件配合Groovy/Shell脚本实现:
以Groovy脚本为例,在子模块POM中添加配置:
<build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>3.1.0</version> <executions> <execution> <phase>initialize</phase> <goals> <goal>exec</goal> </goals> <configuration> <executable>groovy</executable> <arguments> <argument>-e</argument> <argument> def parentVersion = project.parent.version; println("当前父POM版本:" + parentVersion); // 这里可以加自定义逻辑,比如把版本写入version.txt new File("version.txt").write(parentVersion); </argument> </arguments> </configuration> </execution> </executions> </plugin> </plugins> </build>
执行mvn initialize时,脚本会自动读取并处理父版本号,你可以根据需求扩展更多功能。
内容的提问来源于stack exchange,提问作者Georgi Stoyanov
相关产品推荐
相关产品推荐

