从maven pom检索版本。xml代码中

时间:2020-12-08 23:56:09

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

从maven的pom检索版本号的最简单方法是什么?xml代码,即。编程吗?

7 个解决方案

#1


182  

Assuming you're using Java, you can

假设您正在使用Java,那么您可以这样做

  1. Create a .properties file in (most commonly) your src/main/resources directory (but in step 4 you could tell it to look elsewhere).

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

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

    使用项目版本的标准Maven属性设置.properties文件中某些属性的值: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).

    在Java代码中,将属性文件中的值作为来自类路径的资源加载(关于如何实现这一点的大量示例,这里有一个例子)。

  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 here but you mostly just do this in your pom:

    在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 中添加的任意属性等。资源筛选,加上Maven配置文件,可以在构建时给您变量构建行为。当您在运行时使用-PmyProfile指定一个概要文件时,它可以启用可以在构建中显示的属性。

#2


64  

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

打包的工件包含一个META-INF/maven/${groupId}/${artifactId}/pom。属性文件,内容如下:

#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 package phase 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.

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

#3


40  

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 dynamically during 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.*:my-artifact:jar:1.0-SNAPSHOT
de.scrum-master.*
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.*/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());
  }
}

#4


34  

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.

我发现这个方法比较简单。

#5


11  

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

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

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的版本)在存档。

#6


11  

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-info is very useful.

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

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

您只需激活执行器,并在应用程序中添加所需的属性。属性或application.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
info.build.artifact=@project.artifactId@
info.build.name=@project.name@
info.build.description=@project.description@
info.build.version=@project.version@

#7


5  

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

#1


182  

Assuming you're using Java, you can

假设您正在使用Java,那么您可以这样做

  1. Create a .properties file in (most commonly) your src/main/resources directory (but in step 4 you could tell it to look elsewhere).

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

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

    使用项目版本的标准Maven属性设置.properties文件中某些属性的值: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).

    在Java代码中,将属性文件中的值作为来自类路径的资源加载(关于如何实现这一点的大量示例,这里有一个例子)。

  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 here but you mostly just do this in your pom:

    在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 中添加的任意属性等。资源筛选,加上Maven配置文件,可以在构建时给您变量构建行为。当您在运行时使用-PmyProfile指定一个概要文件时,它可以启用可以在构建中显示的属性。

#2


64  

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

打包的工件包含一个META-INF/maven/${groupId}/${artifactId}/pom。属性文件,内容如下:

#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 package phase 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.

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

#3


40  

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 dynamically during 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.*:my-artifact:jar:1.0-SNAPSHOT
de.scrum-master.*
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.*/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());
  }
}

#4


34  

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.

我发现这个方法比较简单。

#5


11  

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

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

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的版本)在存档。

#6


11  

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-info is very useful.

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

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

您只需激活执行器,并在应用程序中添加所需的属性。属性或application.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
info.build.artifact=@project.artifactId@
info.build.name=@project.name@
info.build.description=@project.description@
info.build.version=@project.version@

#7


5  

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