3

I have two versions in my projects.

  1. The version in my POM.xml which is used when the project is packaged, etc.
  2. The version I have put in a constant in my code so I can use it during runtime when I log, etc.

These should of course be the same, but sometimes I forget to change one or the other.

Is there a good way to define this version only once and have it used by both maven and code during runtime?

Svish
  • 152,914
  • 173
  • 462
  • 620

3 Answers3

4

http://www.sonatype.com/books/mvnref-book/reference/resource-filtering-sect-description.html

Have a look at this, you should have a properties file, which has a certain property which refers to the version number. And using filtering you can set the version same both in maven artifact and application.

Himanshu Bhardwaj
  • 4,038
  • 3
  • 17
  • 36
2

When you package your application using Maven, Maven will generate a directory META-INF/maven/<groupId>/<artifactId>/pom.properties. That file contains the version of your project according to the POM, and you could load that file from the JAR file on runtime in order to read your version number.

Only thing is, this file does only exist in a packaged project (be it a JAR, a WAR or an EAR). You might want to write some fallback mechanism for when you are running the code from your workbench.

mthmulders
  • 9,483
  • 4
  • 37
  • 54
1

This is some code that I usually use when I want the version specified in the pom file.

private final static String GROUP_ID = "my.group";
private final static String ARTIFACT_ID = "my-artifact";

private String getVersion() {
    String propFileName = "META-INF/maven/" + GROUP_ID + "/" + ARTIFACT_ID + "/pom.properties";
    Properties properties = new Properties();
    String version = "n/a";

    try {
        InputStream inStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(propFileName);

        if (inStream != null) {
            properties.load(inStream);
            version = properties.getProperty("version", "n/a");
        }
    } catch (IOException e) { }
    return version;
}

And as mthmulders says in his answer, this file does only exist in a packaged project (in the final war/jar/any, not in the working directory).

Jean-Rémy Revy
  • 5,607
  • 3
  • 39
  • 65
maba
  • 47,113
  • 10
  • 108
  • 118