Embedding the maven version number

If you build a jar file with maven, it helpfully embeds a properties file so that you can pull out information about the build environment. You just need some code like this.

  String path = "/META-INF/maven/groupId/artifactId/"
  InputStream stream = getClass().getResourceAsStream(path);
  Properties props = new Properties();
  System.out.println("my version is" + props.get("version"));

Now, this is all well and good, but it only works when you’ve built the artifact1. In development, it simply doesn’t exist, and you have to work around that in the code.

It would be much simpler if you could just compile in the version as a constant.

Thankfully, when I asked the question on the maven-users list, Lee Meador showed me an example. In a nutshell, you use ant to generate an extra source file containing the version number.

First, you need a little ant script to emit some Java code.

            package com.mycompany.myproject;
            /** Automatically generated by ant. */
            public class Version {
              public static final String VERSION = "${version}";

Then, you need to add the antrun plugin to your pom.xml.


This binds the antrun:run goal to the “generate-sources” phase (which happens right at the start of the build). It runs the little ant script above, passing in the correct properties. Then, it adds a new source directory, so maven knows to compile that one file that we’re generating.

When I initially tried this in Eclipse, it couldn’t find the Version class. However, running “Maven → Update Project Configuration” added target/generated-sources as a new source folder. And everything worked just fine after that. If you don’t have that option, you need to update to a new version of m2eclipse. Deleting and reimporting the project should sort it out.

This might seem like a fairly complicated way of solving the problem of getting the maven version number. But it’s more reliable than any of the other methods I have seen, so I’m pretty happy with it.

1 Yeah, I know. American spelling. I’ve been polluted by years of exposure.