1. Overview
In this short tutorial, we'll take a look at how to use variables defined inside Maven's pom.xml from a Java application.
2. Plugin Configuration
Throughout this example, we'll use the Maven Properties Plugin.
This plugin will bind to the generate-resources phase and create a file containing the variables defined in our pom.xml during compilation. We can then read that file at runtime to get the values.
Let's start by including the plugin in our project:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>properties-maven-plugin</artifactId>
<version>1.0.0</version>
<executions>
<execution>
<phase>generate-resources</phase>
<goals>
<goal>write-project-properties</goal>
</goals>
<configuration>
<outputFile>${project.build.outputDirectory}/properties-from-pom.properties</outputFile>
</configuration>
</execution>
</executions>
</plugin>
Next, we'll continue by providing a value to our variable. Furthermore, since we're defining them inside the pom.xml, we can use Maven placeholders as well:
<properties>
<name>${project.name}</name>
<my.awesome.property>property-from-pom</my.awesome.property>
</properties>
3. Reading Properties
Now it's time to access our property from the configuration. Let's create a simple utility class to read the properties from a file on the classpath:
public class PropertiesReader {
private Properties properties;
public PropertiesReader(String propertyFileName) throws IOException {
InputStream is = getClass().getClassLoader()
.getResourceAsStream(propertyFileName);
this.properties = new Properties();
this.properties.load(is);
}
public String getProperty(String propertyName) {
return this.properties.getProperty(propertyName);
}
}
Next, we simply write a small test case that reads our values:
PropertiesReader reader = new PropertiesReader("properties-from-pom.properties");
String property = reader.getProperty("my.awesome.property");
Assert.assertEquals("property-from-pom", property);
4. Conclusion
In this article, we went through the process of reading values defined in the pom.xml using the Maven Properties Plugin.
As always, all the code is available over on GitHub.