tags:

views:

96

answers:

1

I have noticed that in a Maven artifact's JAR, the project.version attribute is included in two files:

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?

+5  A: 

You should not need to access Maven-specific files to get the version information of any given library/class.

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 enough Unfortunately Maven does not write the correct information to the manifest as well by default!

Instead one has to modify the <archive> configuration element of the maven-jar-plugin to set addDefaultImplementationEntries and addDefaultSpecificationEntries to true, like this:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <inherited>true</inherited>
    <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.

Detailed documentation of the <archive> element can be found in the Maven Archive documentation.

Joachim Sauer
Hi @Joachim, just tried this, and it doesn't seem to be the case. I can add this version by adding <archive><manifestEntries><Implementation-Version>${project.version}</Implementation-Version></manifestEntries></archive> to the maven-jar-plugin <configuration/> entity in the POM. Once I've done that, getClass().getPackage().getImplementationVersion() works a treat - thanks!
Alison
Indeed, it seems that Maven doesn't do The Right Thing™, but our company pom is configured to do that. Simply configure the `<archive>` configuration of the `maven-jar-plugin` to set `addDefaultImplementationEntries` to `true` and it should work: http://maven.apache.org/shared/maven-archiver/index.html
Joachim Sauer
+1 Thanks for pointing that out.
Pascal Thivent
@Joachim thanks for the extra info - glad we've managed to sort this out. Would it be best to modify your answer so we have a perfect response?
Alison