javamavenversion

Retrieve version from maven pom.xml in code


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


Solution

  • 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, but here's an example for starters).

    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 <properties>, etc. Resource filtering, combined with Maven profiles, can give you 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.