问题
我注意到在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;
}