1、POM的版本占位符

从Maven 3.5.0-beta-1开始可以使用${revision}, ${sha1} and/or ${changelist}作为 pom 文件中版本的占位符。

详见:https://maven.apache.org/docs/3.5.0-beta-1/release-notes.html

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.cc.x</groupId>
  <artifactId>product-x</artifactId>
  <packaging>pom</packaging>
  
  <!-- 方式1:简单的情况,比较简洁 --> 
  <version>${revision}</version>
  <!-- 方式2:通过不同属性的组合来提高灵活性-->
  <version>${revision}${sha1}${changelist}</version>
  
  <properties>
    <!-- 通过属性来配置占位符.可被命令行的参数覆盖,如:-Drevision=1.4.2 -->
    <revision>1.3.1</revision>
    <changelist>-SNAPSHOT</changelist>
    <sha1/>
	</properties>
</project>

通过以上的配置,执行mvn package便能完成打包。

但是,如果你想通过mvn install或者mvn deploy命令将生成的JAR包安装到存储库(repository),则必须配合插件flatten-maven-plugin来完成。

如果你不使用flatten-maven-plugin,则JAR包依然会被安装到存储库,但该JAR包将不能被Maven使用,因为安装时会把原始pom.xml的内容安装到存储库中(即占位符并未被替换),所以maven将不能定位到该JAR的坐标。


2、flatten-maven-plugin

  <plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>flatten-maven-plugin</artifactId>
    <version>1.6.0</version>
    <configuration>
        <!-- 是否更新pom文件 -->
        <updatePomFile>true</updatePomFile>
        <flattenMode>resolveCiFriendliesOnly</flattenMode>
    </configuration>
    <executions>
        <execution>
            <id>flatten</id>
            <phase>process-resources</phase>
            <goals>
                <goal>flatten</goal>
            </goals>
        </execution>
        <execution>
            <id>flatten.clean</id>
            <phase>clean</phase>
            <goals>
                <goal>clean</goal>
            </goals>
        </execution>
    </executions>
</plugin>

该插件会在pom.xml相同路径下创建.flattened-pom.xml文件,该.flattened-pom.xml文件被替换过版本变量,在install或deploy的时候将使用该文件的内容安装到存储库中。


需要注意的是,.flattened-pom.xml文件还是不要提交到Git仓库了哦

插件的更多信息可参考官网:https://www.mojohaus.org/flatten-maven-plugin/


3、聚合工程

与普通的maven工程每多大区别,在parent模块中使用版本的占位符,子模块在的<parent>元素中也使用占位符,例如有如下子模块

<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.cc.x</groupId>
    <artifactId>product-x</artifactId>
    <!-- 使用版本占位符,同时添加relativePath(也可忽略relativePath,默认为"../pom.xml")-->
    <version>${revision}</version>
    <relativePath>../pom.xml</relativePath>
  </parent>
  
  <artifactId>x-application</artifactId>
  <packaging>jar</packaging>
  <dependencies>
    
  </dependencies>
</project>