Java 在运行时获取 Maven 工件版本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2712970/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get Maven artifact version at runtime
提问by Armand
I have noticed that in a Maven artifact's JAR, the project.version attribute is included in two files:
我注意到在 Maven 工件的 JAR 中,project.version 属性包含在两个文件中:
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?
有没有推荐的在运行时读取这个版本的方法?
采纳答案by Joachim Sauer
You should not need to access Maven-specific files to get the version information of any given library/class.
您不需要访问特定于 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 enoughUnfortunately Maven does not write the correct information to the manifest as well by default!
您可以简单地使用getClass().getPackage().getImplementationVersion()
获取存储在 .jar-files 中的版本信息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
, like this:
相反,必须修改to set和to的<archive>
配置元素,如下所示:maven-jar-plugin
addDefaultImplementationEntries
addDefaultSpecificationEntries
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>
Ideally this configuration should be put into the company pom
or another base-pom.
理想情况下,此配置应放入公司pom
或其他 base-pom 中。
Detailed documentation of the <archive>
element can be found in the Maven Archive documentation.
<archive>
可以在Maven 存档文档 中找到该元素的详细文档。
回答by Rob
To follow up the answer above, for a .war
artifact, I found I had to apply the equivalent configuration to maven-war-plugin
, rather than maven-jar-plugin
:
为了跟进上面的答案,对于.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>
This added the version information to MANIFEST.MF
in the project's .jar
(included in WEB-INF/lib
of the .war
)
这将版本信息添加到MANIFEST.MF
项目的.jar
(包含在WEB-INF/lib
中.war
)
回答by mysomic
Here's a method for getting the version from the pom.properties, falling back to getting it from the manifest
这是一种从 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;
}
回答by will
I spent some time on the two main approaches here and they didn't work-out for me. I am using Netbeans for the builds, may be there's more going on there. I had some errors and warnings from Maven 3 with some constructs, but I think those were easy to correct. No biggie.
我在这两种主要方法上花了一些时间,但它们对我不起作用。我正在使用 Netbeans 进行构建,可能还有更多内容。我有一些来自 Maven 3 的错误和警告以及一些构造,但我认为这些很容易纠正。没什么大不了的。
I did find an answer that looks maintainable and simple to implement in this article on DZone:
我确实在 DZone 上的这篇文章中找到了一个看起来可维护且易于实现的答案:
I already have a resources/config sub-folder, and I named my file: app.properties, to better reflect the kind of stuff we may keep there (like a support URL, etc.).
我已经有一个 resources/config 子文件夹,我将我的文件命名为:app.properties,以更好地反映我们可能保留在那里的内容(如支持 URL 等)。
The only caveat is that Netbeans gives a warning that the IDE needs filtering off. Not sure where/how. It has no effect at this point. Perhaps there's a work around for that if I need to cross that bridge. Best of luck.
唯一需要注意的是,Netbeans 会发出 IDE 需要过滤掉的警告。不确定在哪里/如何。在这一点上它没有任何影响。如果我需要过那座桥,也许可以解决这个问题。祝你好运。
回答by Luke Hutchison
To get this running in Eclipse, as well as in a Maven build, you should add the addDefaultImplementationEntries
and addDefaultSpecificationEntries
pom entries as described in other replies, then use the following code:
要使其在 Eclipse 以及 Maven 构建中运行,您应该按照其他回复中的描述添加addDefaultImplementationEntries
和addDefaultSpecificationEntries
pom 条目,然后使用以下代码:
public synchronized static final String getVersion() {
// Try to get version number from pom.xml (available in Eclipse)
try {
String className = getClass().getName();
String classfileName = "/" + className.replace('.', '/') + ".class";
URL classfileResource = getClass().getResource(classfileName);
if (classfileResource != null) {
Path absolutePackagePath = Paths.get(classfileResource.toURI())
.getParent();
int packagePathSegments = className.length()
- className.replace(".", "").length();
// Remove package segments from path, plus two more levels
// for "target/classes", which is the standard location for
// classes in Eclipse.
Path path = absolutePackagePath;
for (int i = 0, segmentsToRemove = packagePathSegments + 2;
i < segmentsToRemove; i++) {
path = path.getParent();
}
Path pom = path.resolve("pom.xml");
try (InputStream is = Files.newInputStream(pom)) {
Document doc = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().parse(is);
doc.getDocumentElement().normalize();
String version = (String) XPathFactory.newInstance()
.newXPath().compile("/project/version")
.evaluate(doc, XPathConstants.STRING);
if (version != null) {
version = version.trim();
if (!version.isEmpty()) {
return version;
}
}
}
}
} catch (Exception e) {
// Ignore
}
// Try to get version number from maven properties in jar's META-INF
try (InputStream is = getClass()
.getResourceAsStream("/META-INF/maven/" + MAVEN_PACKAGE + "/"
+ MAVEN_ARTIFACT + "/pom.properties")) {
if (is != null) {
Properties p = new Properties();
p.load(is);
String version = p.getProperty("version", "").trim();
if (!version.isEmpty()) {
return version;
}
}
} catch (Exception e) {
// Ignore
}
// Fallback to using Java API to get version from MANIFEST.MF
String version = null;
Package pkg = getClass().getPackage();
if (pkg != null) {
version = pkg.getImplementationVersion();
if (version == null) {
version = pkg.getSpecificationVersion();
}
}
version = version == null ? "" : version.trim();
return version.isEmpty() ? "unknown" : version;
}
If your Java build puts target classes somewhere other than "target/classes", then you may need to adjust the value of segmentsToRemove.
如果您的 Java 构建将目标类放在“目标/类”之外的某个地方,那么您可能需要调整 segmentToRemove 的值。
回答by u3758939
I am using maven-assembly-plugin
for my maven packaging. The usage of Apache Maven Archiverin Joachim Sauer's answercould also work:
我maven-assembly-plugin
用于我的 maven 包装。在Joachim Sauer 的回答中使用Apache Maven Archiver也可以:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
</manifest>
</archive>
</configuration>
<executions>
<execution .../>
</executions>
</plugin>
Because archiever is one of maven shared components, it could be used by multiple maven building plugins, which could also have conflict if two or more plugins introduced, including archive
configuration inside.
因为archiever是maven共享组件之一,它可以被多个maven构建插件使用,如果引入两个或多个插件,包括archive
里面的配置,也会产生冲突。
回答by onderbewustzijn
Java 8 variant for EJB in war file with maven project. Tested on EAP 7.0.
Maven 项目的 war 文件中 EJB 的 Java 8 变体。在 EAP 7.0 上测试。
@Log4j // lombok annotation
@Startup
@Singleton
public class ApplicationLogic {
public static final String DEVELOPMENT_APPLICATION_NAME = "application";
public static final String DEVELOPMENT_GROUP_NAME = "com.group";
private static final String POM_PROPERTIES_LOCATION = "/META-INF/maven/" + DEVELOPMENT_GROUP_NAME + "/" + DEVELOPMENT_APPLICATION_NAME + "/pom.properties";
// In case no pom.properties file was generated or wrong location is configured, no pom.properties loading is done; otherwise VERSION will be assigned later
public static String VERSION = "No pom.properties file present in folder " + POM_PROPERTIES_LOCATION;
private static final String VERSION_ERROR = "Version could not be determinated";
{
Optional.ofNullable(getClass().getResourceAsStream(POM_PROPERTIES_LOCATION)).ifPresent(p -> {
Properties properties = new Properties();
try {
properties.load(p);
VERSION = properties.getProperty("version", VERSION_ERROR);
} catch (Exception e) {
VERSION = VERSION_ERROR;
log.fatal("Unexpected error occured during loading process of pom.properties file in META-INF folder!");
}
});
}
}
回答by Reema
On my spring boot application, the solution from the accepted answer worked until I recently updated my jdk to version 12. Tried all the other answers as well and couldn't get that to work.
在我的 Spring Boot 应用程序中,接受的答案中的解决方案一直有效,直到我最近将 jdk 更新到版本 12。也尝试了所有其他答案,但无法使其正常工作。
At that point, I added the below line to the first class of my spring boot application, just after the annotation @SpringBootApplication
那时,我将以下行添加到我的 Spring Boot 应用程序的第一类中,就在注释之后 @SpringBootApplication
@PropertySources({
@PropertySource("/META-INF/maven/com.my.group/my-artefact/pom.properties")
})
Later I use the below to get the value from the properties file in whichever class I want to use its value and appVersion
gets the project version to me:
后来我使用下面的从我想使用它的值的任何类中的属性文件中appVersion
获取值并将项目版本提供给我:
@Value("${version}")
private String appVersion;
Hope that helps someone.
希望能帮助某人。