logo

Load POM Properties in Java

Last Updated: 2021-11-19

Solution

e.g. Load version from POM:

  1. add version.properties to src/main/resources
version = ${project.version}
  1. add that file to resources in pom and set filtering to true
<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>
  1. read from Java
Properties prop = new Properties();
prop.load(this.getClass().getResourceAsStream("/version.properties"));
String version = prop.getProperty("version");

How it works

Properties in Maven(pom)

  • env.X: shell's environment variables, all upper-case, e.g. env.JAVA_HOME
  • project.x: inside pom, e.g. <project><version>1.0</version></project> -> ${project.version}
  • settings.x: defined in ~/.m2/settings.xml
  • Java System Properties: anything in System.getProperties, e.g. ${java.home}
  • User defined: defined in <properties /> in pom

Filtering

Basically the ${} will be replaced by properties in compiling. In this example, enabling filtering will replace ${project.version} with the content in pom <version>0.3.5</version> as 0.3.5