Java 在代码中从 maven pom.xml 中检索版本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3697449/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 03:36:41  来源:igfitidea点击:

Retrieve version from maven pom.xml in code

javamaven-2version

提问by mikhail

What is the simplest way to retrieve version number from maven's pom.xml in code, i.e., programatically?

在代码中,即以编程方式从 maven 的 pom.xml 中检索版本号的最简单方法是什么?

采纳答案by Alex Miller

Assuming you're using Java, you can

假设您使用的是 Java,您可以

  1. Create a .propertiesfile in (most commonly) your src/main/resourcesdirectory (but in step 4 you could tell it to look elsewhere).

  2. Set the value of some property in your .propertiesfile using the standard Maven property for project version: foo.bar=${project.version}

  3. In your Java code, load the value from the properties file as a resource from the classpath (google for copious examples of how to do this, but here's an example for starters).

  4. In Maven, enable resource filtering - this will cause Maven to copy that file into your output classes and translate the resource during that copy, interpreting the property. You can find some info herebut you mostly just do this in your pom:

  1. .properties在(最常见)您的src/main/resources目录中创建一个文件(但在第 4 步中,您可以告诉它在其他地方查找)。

  2. .properties使用项目版本的标准 Maven 属性设置文件中某些属性的值: foo.bar=${project.version}

  3. 在您的 Java 代码中,将属性文件中的值作为类路径中的资源加载(谷歌有关如何执行此操作的大量示例,但这里是初学者的示例)。

  4. 在 Maven 中,启用资源过滤 - 这将导致 Maven 将该文件复制到您的输出类中,并在该复制期间翻译资源,解释属性。你可以在这里找到一些信息但你大多只是在你的 pom 中这样做:

    <build>
      <resources>
        <resource>
          <directory>src/main/resources</directory>
          <filtering>true</filtering>
        </resource>
      </resources>   
    </build>

You can also get to other standard properties like project.name, project.description, or even arbitrary properties you put in your pom <properties>, etc. Resource filtering, combined with Maven profiles, can give you variable build behavior at build time. When you specify a profile at runtime with -PmyProfile, that can enable properties that then can show up in your build.

您还可以访问其他标准属性,例如project.name, project.description,甚至是您放入 pom 中的任意属性<properties>等。资源过滤与 Maven 配置文件相结合,可以在构建时为您提供可变的构建行为。当您在运行时使用 指定配置文件时-PmyProfile,它可以启用随后可以显示在您的构建中的属性。

回答by Pascal Thivent

Packaged artifacts contain a META-INF/maven/${groupId}/${artifactId}/pom.propertiesfile which content looks like:

打包的工件包含一个META-INF/maven/${groupId}/${artifactId}/pom.properties文件,其内容如下所示:

#Generated by Maven
#Sun Feb 21 23:38:24 GMT 2010
version=2.5
groupId=commons-lang
artifactId=commons-lang

Many applications use this file to read the application/jar version at runtime, there is zero setup required.

许多应用程序使用此文件在运行时读取应用程序/jar 版本,需要零设置。

The only problem with the above approach is that this file is (currently) generated during the packagephase and will thus not be present during tests, etc (there is a Jira issue to change this, see MJAR-76). If this is an issue for you, then the approach described by Alex is the way to go.

上述方法的唯一问题是该文件是(当前)在package阶段期间生成的,因此在测试等期间不会出现(有一个 Jira 问题可以改变这一点,请参阅MJAR-76)。如果这对您来说是个问题,那么 Alex 描述的方法就是您要走的路。

回答by adam.lofts

There is also the method described in Easy way to display your apps version number using Maven:

还有使用 Maven 显示应用程序版本号的简单方法中描述的方法:

Add this to pom.xml

将此添加到 pom.xml

<build>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-jar-plugin</artifactId>
      <configuration>
        <archive>
          <manifest>
            <mainClass>test.App</mainClass>
            <addDefaultImplementationEntries>
              true
            </addDefaultImplementationEntries>
          </manifest>
        </archive>
      </configuration>
    </plugin>
  </plugins>
</build>

Then use this:

然后使用这个:

App.class.getPackage().getImplementationVersion()

I have found this method to be simpler.

我发现这种方法更简单。

回答by feder

Use this Library for the ease of a simple solution. Add to the manifest whatever you need and then query by string.

使用这个库来简化一个简单的解决方案。将您需要的任何内容添加到清单中,然后按字符串查询。

 System.out.println("JAR was created by " + Manifests.read("Created-By"));

http://manifests.jcabi.com/index.html

http://manifests.jcabi.com/index.html

回答by electrobabe

If you use mvn packaging such as jar or war, use:

如果使用 jar 或 war 等 mvn 包装,请使用:

getClass().getPackage().getImplementationVersion()

It reads a property "Implementation-Version" of the generated META-INF/MANIFEST.MF (that is set to the pom.xml's version) in the archive.

它读取存档中生成的 META-INF/MANIFEST.MF(设置为 pom.xml 的版本)的属性“Implementation-Version”。

回答by coolnodje

To complement what @kieste has posted, which I think is the best way to have Maven build informations available in your code if you're using Spring-boot: the documentation at http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#production-ready-application-infois very useful.

为了补充@kieste 发布的内容,如果您使用 Spring-boot,我认为这是在您的代码中提供 Maven 构建信息的最佳方式:http://docs.spring.io/spring-boot/ 上的文档docs/current/reference/htmlsingle/#production-ready-application-info非常有用。

You just need to activate actuators, and add the properties you need in your application.propertiesor application.yml

您只需要激活执行器,并在您的application.propertiesapplication.yml

Automatic property expansion using Maven

You can automatically expand info properties from the Maven project using resource filtering. If you use the spring-boot-starter-parent you can then refer to your Maven ‘project properties' via @..@ placeholders, e.g.

project.artifactId=myproject
project.name=Demo
project.version=X.X.X.X
project.description=Demo project for info endpoint
[email protected]@
[email protected]@
[email protected]@
[email protected]@

回答by kriegaex

The accepted answer may be the best and most stable way to get a version number into an application statically, but does not actually answer the original question: How to retrieve the artifact's version number from pom.xml? Thus, I want to offer an alternative showing how to do it dynamicallyduring runtime:

接受的答案可能是将版本号静态地获取到应用程序中的最佳和最稳定的方法,但实际上并没有回答原始问题:如何从 pom.xml 检索工件的版本号?因此,我想提供一种替代方法,展示如何在运行时动态执行此操作:

You can use Maven itself. To be more exact, you can use a Maven library.

您可以使用 Maven 本身。更准确地说,您可以使用 Maven 库。

<dependency>
  <groupId>org.apache.maven</groupId>
  <artifactId>maven-model</artifactId>
  <version>3.3.9</version>
</dependency>

And then do something like this in Java:

然后在 Java 中做这样的事情:

package de.scrum_master.app;

import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;

import java.io.FileReader;
import java.io.IOException;

public class Application {
    public static void main(String[] args) throws IOException, XmlPullParserException {
        MavenXpp3Reader reader = new MavenXpp3Reader();
        Model model = reader.read(new FileReader("pom.xml"));
        System.out.println(model.getId());
        System.out.println(model.getGroupId());
        System.out.println(model.getArtifactId());
        System.out.println(model.getVersion());
    }
}

The console log is as follows:

控制台日志如下:

de.scrum-master.stackoverflow:my-artifact:jar:1.0-SNAPSHOT
de.scrum-master.stackoverflow
my-artifact
1.0-SNAPSHOT


Update 2017-10-31:In order to answer Simon Sobisch's follow-up question I modified the example like this:

2017年 10 月 31 日更新:为了回答 Simon Sobisch 的后续问题,我对示例进行了如下修改:

package de.scrum_master.app;

import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Application {
  public static void main(String[] args) throws IOException, XmlPullParserException {
    MavenXpp3Reader reader = new MavenXpp3Reader();
    Model model;
    if ((new File("pom.xml")).exists())
      model = reader.read(new FileReader("pom.xml"));
    else
      model = reader.read(
        new InputStreamReader(
          Application.class.getResourceAsStream(
            "/META-INF/maven/de.scrum-master.stackoverflow/aspectj-introduce-method/pom.xml"
          )
        )
      );
    System.out.println(model.getId());
    System.out.println(model.getGroupId());
    System.out.println(model.getArtifactId());
    System.out.println(model.getVersion());
  }
}

回答by ketankk

    <build>
            <finalName>${project.artifactId}-${project.version}</finalName>
            <pluginManagement>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-war-plugin</artifactId>
                        <version>3.2.2</version>
                        <configuration>
                            <failOnMissingWebXml>false</failOnMissingWebXml>
                            <archive>
                                <manifest>
                                    <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
                                    <addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
                                </manifest>
                            </archive>
                        </configuration>
                    </plugin>
                 </plugins>
            </pluginManagement>
</build>

Get Version using this.getClass().getPackage().getImplementationVersion()

获取版本使用 this.getClass().getPackage().getImplementationVersion()

PS Don't forget to add:

PS不要忘记添加:

<manifest>
    <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
    <addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
</manifest>

回答by t0r0X

Sometimes the Maven command line is sufficient when scripting something related to the project version, e.g. for artifact retrieval via URL from a repository:

有时,在编写与项目版本相关的脚本时,Maven 命令行就足够了,例如通过 URL 从存储库中检索工件:

mvn help:evaluate -Dexpression=project.version -q -DforceStdout

Usage example:

用法示例:

VERSION=$( mvn help:evaluate -Dexpression=project.version -q -DforceStdout )
ARTIFACT_ID=$( mvn help:evaluate -Dexpression=project.artifactId -q -DforceStdout )
GROUP_ID_URL=$( mvn help:evaluate -Dexpression=project.groupId -q -DforceStdout | sed -e 's#\.#/#g' )
curl -f -S -O http://REPO-URL/mvn-repos/${GROUP_ID_URL}/${ARTIFACT_ID}/${VERSION}/${ARTIFACT_ID}-${VERSION}.jar