tags:

views:

90

answers:

2

What is the simplest way to retrieve version number from maven's pom.xml in code?

+8  A: 

Assuming you're using Java, you can

  1. Create a .properties file in (most commonly) your src/main/resources directory (but in step 4 you could tell it to look elsewhere).

  2. Set the value of some property in your .properties file using the standard Maven property for project version: foo.bar=${project.version}

  3. In your java code, load the value from the properties file as a resource from the classpath (google for copious examples of how to do this).

  4. In Maven, enable resource filtering - this will cause Maven to copy that file into your output classes and translate the resource during that copy, interpreting the property. You can find some info here but you mostly just do this in your pom:

    <build>
      <resources>
        <resource>
          <directory>src/main/resources</directory>
          <filtering>true</filtering>
        </resource>
      </resources>   
    </build>

You can also get to other standard properties like project.name, project.description, or even arbitrary properties you put in your pom etc. Resource filtering, combined with Maven profiles, can you give variable build behavior at build time. When you specify a profile at runtime with -PmyProfile that can enable properties that then can show up in your build.

Alex Miller
+6  A: 

Packaged artifacts contain a META-INF/maven/${groupId}/${artifactId}/pom.properties file which content looks like:

#Generated by Maven
#Sun Feb 21 23:38:24 GMT 2010
version=2.5
groupId=commons-lang
artifactId=commons-lang

Many applications use this file to read the application/jar version at runtime, there is zero setup required.

The only problem with the above approach is that this file is (currently) generated during the package phase and will thus not be present during tests, etc (there is a Jira issue to change this, see MJAR-76). If this is an issue for you, then the approach described by Alex is the way to go.

Pascal Thivent