在运行时获取 Maven 工件版本

新手上路,请多包涵

我注意到在 Maven 工件的 JAR 中,project.version 属性包含在两个文件中:

 META-INF/maven/${groupId}/${artifactId}/pom.properties
META-INF/maven/${groupId}/${artifactId}/pom.xml

有没有推荐的方法在运行时阅读这个版本?

原文由 Armand 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 947
2 个回答

您不需要访问特定于 Maven 的文件来获取任何给定库/类的版本信息。

您可以简单地使用 getClass().getPackage().getImplementationVersion() 来获取存储在 .jar 文件中的版本信息 MANIFEST.MF 。幸运的是 Maven 足够聪明不幸的是,默认情况下,Maven 也不会将正确的信息写入清单!

Instead one has to modify the <archive> configuration element of the maven-jar-plugin to set addDefaultImplementationEntries and addDefaultSpecificationEntries to true ,像这样:

 <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <configuration>
        <archive>
            <manifest>
                <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
                <addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
            </manifest>
        </archive>
    </configuration>
</plugin>

理想情况下,此配置应放入公司 pom 或其他 base-pom。

<archive> 元素的详细文档可以在 Maven 存档文档 中找到。

原文由 Joachim Sauer 发布,翻译遵循 CC BY-SA 3.0 许可协议

为了跟进上面的答案,对于 .war 工件,我发现我必须将等效配置应用到 maven-war-plugin ,而不是 maven-jar-plugin

 <plugin>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.1</version>
    <configuration>
        <archive>
            <manifest>
                <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
                <addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
            </manifest>
        </archive>
    </configuration>
</plugin>

这将版本的信息添加到 MANIFEST.MF WEB-INF/lib 项目的 .jar .war

原文由 Rob 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题