1. Overview

In this short tutorial, we'll look at how we can pass arguments to Maven using the command line.

2. Maven Properties 

Maven properties are value placeholders. First, we need to define them under the properties tag in our pom.xml file:

<properties>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <start-class>com.example.Application</start-class>
    <commons.version>2.5</commons.version>
</properties>

Then, we can use them inside other tags. For example, in this case, we'll use the “commons.version” value in our commons-io dependency:

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>{commons.version}</version>
</dependency>

In fact, we can use these properties anywhere in the pom.xml, such as in the build, package, or plugin sections.

3. Define Placeholders for Properties

Sometimes, we don't know a property value at development time. In this case, we can leave a placeholder instead of a value using the syntax ${some_property}, and Maven will override the placeholder value at runtime. Let's set a placeholder for COMMON_VERSION_CMD:

<properties>
    <maven.compiler.source>1.7</maven.compiler.source>
    <commons.version>2.5</commons.version>
    <version>${COMMON_VERSION_CMD}</version>
</properties>

4. Passing an Argument to Maven

Now, let's run Maven from our terminal as we usually do, with the package command, for example. But in this case, let's also add the notation -D followed by a property name:

mvn package -DCOMMON_VERSION_CMD=2.5

Maven will use the value (2.5) passed as an argument to replace the COMMON_VERSION_CMD property set in our pom.xml. This is not limited to the package command — we can pass arguments together with any Maven command, such as install, test, or build.

5. Conclusion

In this article, we looked at how to pass parameters to Maven from the command line. By using this approach, instead of modifying the pom.xml or any static configuration, we can provide properties dynamically.

Generic bottom

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

>> CHECK OUT THE COURSE
guest
0 Comments
Inline Feedbacks
View all comments