在运行时获取 Maven 工件版本 [英] Get Maven artifact version at runtime
问题描述
我注意到在 Maven 工件的 JAR 中,project.version 属性包含在两个文件中:
I have noticed that in a Maven artifact's JAR, the project.version attribute is included in two files:
META-INF/maven/${groupId}/${artifactId}/pom.properties
META-INF/maven/${groupId}/${artifactId}/pom.xml
有没有推荐的在运行时读取这个版本的方法?
Is there a recommended way to read this version at runtime?
推荐答案
您不需要访问特定于 Maven 的文件来获取任何给定库/类的版本信息.
You should not need to access Maven-specific files to get the version information of any given library/class.
您可以简单地使用 getClass().getPackage().getImplementationVersion()
来获取存储在 .jar 文件 MANIFEST.MF
中的版本信息.幸运的是 Maven 足够聪明 不幸的是,Maven 默认情况下也不会将正确的信息写入清单!
You can simply use getClass().getPackage().getImplementationVersion()
to get the version information that is stored in a .jar-files MANIFEST.MF
. Luckily Maven is smart enough Unfortunately Maven does not write the correct information to the manifest as well by default!
相反,必须修改 maven-jar-plugin
的
配置元素以设置 addDefaultImplementationEntries
和 addDefaultSpecificationEntries
到 true
,像这样:
Instead one has to modify the <archive>
configuration element of the maven-jar-plugin
to set addDefaultImplementationEntries
and addDefaultSpecificationEntries
to true
, like this:
<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.
Ideally this configuration should be put into the company pom
or another base-pom.
元素的详细文档可以在 Maven 存档文档.
Detailed documentation of the <archive>
element can be found in the Maven Archive documentation.
这篇关于在运行时获取 Maven 工件版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!