You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法在MANIFEST.MF中读取exec-maven-plugin设置的Git提交Hash属性

MANIFEST.MF中Build-ID字段为空,尽管exec-maven-plugin已成功设置系统属性

我一眼就看出问题所在了——你用exec:java目标执行GetGitHash类的时候,其实是启动了一个独立的JVM进程,你在那个子进程里设置的githash系统属性,完全不会传递回Maven的主进程。这就是为什么控制台能看到子进程输出的0003dfa9,但maven-jar-plugin根本读不到这个值,最终Build-ID只能是空的。

解决思路:让Maven主进程直接拿到Git Hash

我们可以绕开Java类,直接用exec-maven-plugin执行Git命令,然后把输出捕获为Maven属性(主进程能访问的那种),再让maven-jar-plugin读取这个属性。下面是具体步骤:

1. 移除原来的GetGitHash类和exec:java配置

先删掉你写的GetGitHash类,然后替换exec-maven-plugin的配置为直接执行Git命令:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.6.0</version>
    <executions>
        <execution>
            <id>get-git-hash</id>
            <phase>initialize</phase> <!-- 提前到初始化阶段执行,确保后续插件能拿到属性 -->
            <goals>
                <goal>exec</goal> <!-- 用exec目标代替java目标,直接执行系统命令 -->
            </goals>
            <configuration>
                <executable>git</executable>
                <arguments>
                    <argument>rev-parse</argument>
                    <argument>--short</argument>
                    <argument>HEAD</argument>
                </arguments>
                <outputProperty>githash</outputProperty> <!-- 直接把命令输出设为Maven主进程的属性 -->
                <!-- 可选:把输出写入文件备份,方便调试 -->
                <outputFile>${project.build.directory}/git-hash.properties</outputFile>
                <append>false</append>
            </configuration>
        </execution>
    </executions>
</plugin>

2. (可选)添加默认值,处理Git不可用的情况

在pom.xml的<properties>块里设置默认值,这样如果环境中没有Git,Build-ID会显示预设的默认值:

<properties>
    <githash>ZUFALL</githash>
</properties>

3. 保持maven-jar-plugin的配置不变

你原来的配置已经正确引用了${githash},不需要做任何修改:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <version>3.1.0</version>
    <executions>
        <execution>
            <goals>
                <goal>test-jar</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <archive>
            <addMavenDescriptor>false</addMavenDescriptor>
            <manifestEntries>
                <Library-Version>${project.version}</Library-Version>
                <Build-Timestamp>${maven.build.timestamp}</Build-Timestamp>
                <Build-ID>${githash}</Build-ID>
            </manifestEntries>
        </archive>
    </configuration>
</plugin>

为什么这个方案能行?

exec:exec目标是在Maven主进程的上下文里执行命令,outputProperty会直接把命令的输出结果设置为Maven主进程能访问的属性,这样maven-jar-plugin在package阶段就能正常读取${githash}的值了。

验证一下

执行mvn clean package,然后打开生成的JAR文件里的MANIFEST.MF,你会看到Build-ID已经正确填充了Git的短Hash值(比如0003dfa9);如果Git不可用,就会显示预设的默认值ZUFALL。

内容的提问来源于stack exchange,提问作者Enrique Castaneda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 09:18:13