maven父子模块统一管理版本号

背景:

在使用Maven多模块结构工程时,版本管理是一件很繁琐且容易出错的事情。每次升级版本号都要手动调整或者通过mvn versions:set -DnewVerion=xx命令去更改每一个子模块的版本号,非常的不方便

解决方案:

Maven官方文档说:自 Maven 3.5.0-beta-1 开始,可以使用 ${revision}, ${sha1} and/or ${changelist} 这样的变量作为版本占位符。

即在maven多模块项目中,可配合插件flatten-maven-plugin${revision}属性来实现全局版本统一管理。

环境说明

Maven Version:Apache Maven 3.6.0
Maven Plugin:flatten-maven-plugin
IDE: IntelliJ IDEA 2021.3
JDK: 1.8
POM文件:使用占位符${revision}

代码示例

父模块pom

在properties标签中定义revision标签:

<project>
    <modelVersion>4.0.0</modelVersion>
<groupId>com.sky.fly</groupId> <artifactId>fly-parent</artifactId> <version>${revision}</version> <packaging>pom</packaging> <properties> <!-- 全局版本控制,如果要修改版本号,修改此处即可--> <revision>1.0.0-SNAPSHOT</revision>
     ...
</properties> <modules> <module>fly-child1</module> ... </modules> <build> <plugins> <!-- 添加flatten-maven-plugin插件 --> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>flatten-maven-plugin</artifactId> <version>1.3.0</version> <inherited>true</inherited> <executions> <execution> <id>flatten</id> <phase>process-resources</phase> <goals> <goal>flatten</goal> </goals> <configuration> <!-- 避免IDE将 .flattened-pom.xml 自动识别为功能模块 --> <updatePomFile>true</updatePomFile> <flattenMode>resolveCiFriendliesOnly</flattenMode> <pomElements> <parent>expand</parent> <distributionManagement>remove</distributionManagement> <repositories>remove</repositories> </pomElements> </configuration> </execution> <execution> <id>flatten.clean</id> <phase>clean</phase> <goals> <goal>clean</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project>

关键点:
① 父子模块需遵循父子目录层次;
② 在父模块中引入插件flatten-maven-plugin;
③ 修改.gitignore文件,增加一行.flattened-pom.xml;
④ 不可混合使用${revision}和明确字符串版本号,若出现父子模块版本号混合使用${revision}和明确字符串形式如1.0.0.-SNAPSHOT,在mvn package会出现类似如下错误:

子模块配置

子模块可以直接使用${revision}指定父模块的版本:

<project>
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.sky.fly</groupId>
        <artifactId>fly-parent</artifactId>
        <version>${revision}</version>
        <relativePath>../pom.xml</relativePath> 
    </parent>

    <artifactId>fly-child1</artifactId>
    <packaging>jar</packaging>

</project>

install / depoy

执行install/deploy后,会将该模块的pom文件中的${revision}替换为实际的版本,每个模块下都会生成一个.flattened-pom.xml文件。这个文件可以再idea中设置隐藏不可见.

 

基于以上操作,每次版本号变更,只需要修改父模块POM文件中的revision即可

 

参考文献: https://www.cnblogs.com/Baker-Street/p/18090880

 

posted @ 2024-03-23 11:12  Sherlock先生  阅读(1412)  评论(0编辑  收藏  举报