将git版本信息附加到 jar 文件名中

问题

当前工作中,我们使用 Maven 构建 Java 项目,但是未采用 Maven 最佳实践滚动更新版本,反复使用同一版本号。这导致了版本信息丢失,无法追溯到具体的版本。

带来的问题:

  1. 无法在具体版本上进行问题修复,每次都需要更新到最新后进行修复,修复风险人为变大
  2. 查找问题时无法快速定位到具体版本,处理故障的时间在定位版本上就要花费大量时间

解决方案

借用 classifier 插件,将 git 版本信息附加到 jar 文件名中。这样,每次构建时,都会生成一个新的 jar 文件,文件名中包含 git 版本信息,方便后续的版本回溯。

pom.xml

<properties>
<git.hash>${git_hash}</git.hash>
</properties>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.3.0</version>
<executions>
<execution>
<id>generate-jar</id>
<goals>
<goal>jar</goal>
</goals>
<configuration>
<classifier>git_${git.hash}</classifier>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>

生成

通过外置参数,通过命令行传入 git 版本信息,生成 jar 文件。

  • mvnd

    $ mvnd -Dgit_hash=$(git rev-parse --short HEAD) package -Dmaven.test.skip=true
  • mvn

    $ mvn -Dgit_hash=$(git rev-parse --short HEAD) package -Dmaven.test.skip=true

结果

$ ls target/*.jar
target/mvndemo-0.1.0-git_a1742e8.jar target/mvndemo-0.1.0.jar

引用

  • 带版本号引用

    <dependency>
    <groupId>demo</groupId>
    <artifactId>mvndemo</artifactId>
    <version>0.1.0</version>
    <classifier>git_a1742e8</classifier>
    </dependency>
  • 不带版本号引用

    <dependency>
    <groupId>demo</groupId>
    <artifactId>mvndemo</artifactId>
    <version>0.1.0</version>
    </dependency>