Reading properties file from Maven POM file

Arek picture Arek · Aug 22, 2011 · Viewed 72.7k times · Source

I have Maven POM file with some configuration and in the section plugins, I have maven tomcat plugin with some configuration like this:

<configuration>
   <url>http://localhost:8080/manager/html</url>
   <server>tomcat</server>
</configuration>

I'd like to export url setting to some property file for example tomcat.properties with that key:

url=http://localhost:8080/manager/html

And how can I read this key back in my POM file?

Answer

Vineet Reynolds picture Vineet Reynolds · Aug 22, 2011

Maven allows you to define properties in the project's POM. You can do this using a POM file similar to the following:

<project>
    ...
    <properties>
        <server.url>http://localhost:8080/manager/html</server.url>
    </properties>
    ...
    <build>
        <plugins>
            <plugin>
            ...
                <configuration>
                    <url>${server.url}</url>
                    <server>tomcat</server>
                </configuration>
            ...
            </plugin>
        </plugins>
    </build>
</project>

You can avoid specifying the property within the properties tag, and pass the value from the command line as:

mvn -Dserver.url=http://localhost:8080/manager/html some_maven_goal

Now, if you don't want to specify them from the command line and if you need to further isolate these properties from the project POM, into a properties file, then you'll need to use the Properties Maven plugin, and run it's read-project-properties goal in the initialize phase of the Maven lifecycle. The example from the plugin page is reproduced here:

<project>
  <build>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>properties-maven-plugin</artifactId>
        <version>1.0-alpha-2</version>
        <executions>
           <!-- Associate the read-project-properties goal with the initialize phase, to read the properties file. -->
          <execution>
            <phase>initialize</phase>
            <goals>
              <goal>read-project-properties</goal>
            </goals>
            <configuration>
              <files>
                <file>etc/config/dev.properties</file>
              </files>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>