Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

Apache Maven is a powerful build automation tool used primarily for Java projects. Maven uses a Project Object Model or POM which contains information about the project and configuration details to build the project. Inside the POM, we are able to define properties that can be used in the POM itself or any child POM in a multi-module configured project.

Maven properties allow us to define values in one place and use them in several different locations within our project definition.

In this short article, we’ll go through how to configure default values, and then how to use them.

2. Default Values in the POM

Most commonly, we define default values for Maven properties in the POM – to demonstrate this, we’ll create a property that holds a default value for a library dependency. Let’s start by defining the property and its default value in the POM:

<properties>
    <junit.version>4.13</junit.version>
</properties>

In this example, we’ve created a property called junit.version and assigned a default value of 4.13.

3. Default Values in settings.xml

We can also define Maven properties in a user’s settings.xml. This is useful if users need to set their own default values for a property. We define properties and their values in settings.xml in the same way we define them in the POM.

We find settings.xml in the .m2 directory within a user’s home directory.

4. Default Values on the Command Line

We can define default values for properties on the command line when executing a Maven command. In this example, we’re changing the default value of 4.13 to 4.12:

mvn install -Djunit.version=4.12

5. Using Properties in the POM

We can reference our default property values elsewhere in the POM, so let’s go ahead and define the junit dependency and use our property to retrieve the version number:

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>${junit.version}</version>
    </dependency>
</dependencies>

We’re referencing the value junit.version through the use of the ${junit.version} syntax.

6. Conclusion

In this short article, we’ve seen how to define default values for Maven properties in three different ways, and as we can see, they are useful in allowing us to re-use the same value in various places whilst only needing to manage it in a single place.

As always, the example code can be found over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – Maven (eBook) (cat=Maven)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.