If you package your application in a jar
using the maven-jar-plugin
or the maven-assembly-plugin
, an easy way to get the current pom version is to add an entry in the manifest, which is then available from Java.
The secret is to set the addDefaultImplementationEntries
flag to true (and the addDefaultSpecificationEntries
is you also need the artifact id).
jar plugin configuration:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>...</mainClass>
<addDefaultImplementationEntries>
true
</addDefaultImplementationEntries>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
assembly plugin configuration:
<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>
</manifest>
</archive>
</configuration>
<executions>
<execution .../>
</executions>
</plugin>
addDefaultImplementationEntries
instructs Maven to add the following headers to the MANIFEST.MF
of your jar:
Implementation-Title: display-version
Implementation-Version: 1.0-SNAPSHOT
Implementation-Vendor-Id: test
Now you can use this line of code anywhere in your jar to access the version number:
getClass().getPackage().getImplementationVersion()
More information here and here.