Obtaining Maven Version Programatically On Runtime

This is my favorite way of reading Maven project version from runtime.

First on your pom, declare that all files on src/main/resources will be filtered — meaning any placeholder (eg: ${project.version}) will be substituted by Maven.


  ...
  
    
      src/main/resources
      true
    
  

Then create a properties file (eg: myapp.properties) with key-value pair containing the Maven project version

myapp.version=${project.version}

Ensure the file above is configured on your Spring container either using xml:


Or Java annotation:

("classpath:/myapp.properties")
public class TheConfig {
  ...
}

The key-value entry can then be injected on any Java beans living in the container:

public class MyClass {
  ("${myapp.version}") private String version;
  ...
}

Or even spring xml config:


  

Beware that if you have more than 1 Spring container (eg: root and servlet), you need to declare on both, otherwise the injection will fail.

Leave a Reply