Thursday, May 21, 2015

Getting version string from a Maven based web application

When you package a maven project, it will automatically generate a file inside that will contains the version, artifactId and groupId information. These are handy to have and to display for your web application at runtime. One can use a method like following to retrive it.

public class Application {
     private String version;

     public String getVersion() {
        if (version == null) {
            String res = "META-INF/maven/myapp/";
            URL url = Thread.currentThread().getContextClassLoader().getResource(res);
            if (url == null) {
                version = "SNAPSHOT." + Utils.timestamp();
            } else {
                Properties props = Utils.loadProperties(res);
                version = props.getProperty("version");
        return version;


Sounds good? Not too fast! Turns out you have to do little more trick to have this working properly for deployment. By default the maven war plugin will package your classes files into the WEB-INF/classes, but the are in META-INF at the same level, and not in WEB-INF/classes/META-INF! This resulted the above code not finding your resource from classpath!

To fix this, you need to add the following to your pom.xml file:


This will tell maven to jar up your classes along with the in a separate file, then place it in WEB-INF/lib folder instead of using the unpacked WEB-INF/classes version. This forces the to be properly added and read by our getVersion() method.