java 获取maven版本号_在运行时获取Maven工件版本

在Java中,可以使用getClass().getPackage().getImplementationVersion()从MANIFEST.MF获取版本信息。若要从pom.properties读取,可以加载Properties并尝试从/META-INF/maven///pom.properties读取。当这些方法都无法获取版本时,返回空字符串。
摘要由CSDN通过智能技术生成

问题

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

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

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

是否有推荐的方法在运行时读取此版本?

#1 热门回答(226 赞)

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

你可以简单地使用getClass().getPackage().getImplementationVersion()来获取存储在.jar-filesMANIFEST.MF中的版本信息。幸运的是,Maven足够聪明,但默认情况下,Maven也没有向清单写入正确的信息!

相反,必须将maven-jar-plugin的414145828配置元素修改为setaddDefaultImplementationEntries和addDefaultSpecificationEntriestotrue,如下所示:

org.apache.maven.plugins

maven-jar-plugin

true

true

理想情况下,此配置应该放入companypom或另一个基础。

#2 热门回答(65 赞)

为了跟进上面的答案,对于a.warartifact,我发现我必须将等效配置应用到444149585,而不是31414670:

maven-war-plugin

2.1

true

true

这在项目的.jar(包含在.war的WEB-INF/lib中)中添加了版本信息到MANIFEST.MF

#3 热门回答(22 赞)

这是从pom.properties获取版本的方法,后退到从清单中获取它

public synchronized String getVersion() {

String version = null;

// try to load from maven properties first

try {

Properties p = new Properties();

InputStream is = getClass().getResourceAsStream("/META-INF/maven/com.my.group/my-artefact/pom.properties");

if (is != null) {

p.load(is);

version = p.getProperty("version", "");

}

} catch (Exception e) {

// ignore

}

// fallback to using Java API

if (version == null) {

Package aPackage = getClass().getPackage();

if (aPackage != null) {

version = aPackage.getImplementationVersion();

if (version == null) {

version = aPackage.getSpecificationVersion();

}

}

}

if (version == null) {

// we could not compute the version so use a blank

version = "";

}

return version;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值