[java] Retrieve version from maven pom.xml in code

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

This question is related to java maven-2 version

The answer is


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

Add this to 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.


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:

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

When using spring boot, this link might be useful: https://docs.spring.io/spring-boot/docs/2.3.x/reference/html/howto.html#howto-properties-and-configuration

With spring-boot-starter-parent you just need to add the following to your application config file:

# get values from pom.xml
[email protected]@

After that the value is available like this:

@Value("${pom.version}")
private String pomVersion;

With reference to ketankk's answer:

Unfortunately, adding this messed with how my application dealt with resources:

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

But using this inside maven-assemble-plugin's < manifest > tag did the trick:

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

So I was able to get version using

String version = getClass().getPackage().getImplementationVersion();

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:

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

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

And then do something like this in 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:

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());
  }
}

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


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

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.


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.

You just need to activate actuators, and add the properties you need in your application.properties or 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
[email protected]@
[email protected]@
[email protected]@
[email protected]@

    <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()

PS Don't forget to add:

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

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

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

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.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to maven-2

Maven:Non-resolvable parent POM and 'parent.relativePath' points at wrong local POM Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project. Plugin org.apache.maven.plugins:maven-clean-plugin:2.5 or one of its dependencies could not be resolved Maven Error: Could not find or load main class MAVEN_HOME, MVN_HOME or M2_HOME Where is my m2 folder on Mac OS X Mavericks Maven won't run my Project : Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec 'mvn' is not recognized as an internal or external command, operable program or batch file SLF4J: Class path contains multiple SLF4J bindings Create local maven repository

Examples related to version

Which TensorFlow and CUDA version combinations are compatible? How can the default node version be set using NVM? Node - was compiled against a different Node.js version using NODE_MODULE_VERSION 51 Which ChromeDriver version is compatible with which Chrome Browser version? How to find which version of TensorFlow is installed in my system? How to update Ruby Version 2.0.0 to the latest version in Mac OSX Yosemite? What does 'Unsupported major.minor version 52.0' mean, and how do I fix it? Find nginx version? How to check all versions of python installed on osx and centos How can I specify the required Node.js version in package.json?