1. Overview
1.概述
In this short tutorial, we’ll look at how we can pass arguments to Maven using the command line.
在这个简短的教程中,我们将了解如何使用命令行向Maven传递参数。
2. Maven Properties
2.Maven属性
Maven properties are value placeholders. First, we need to define them under the properties tag in our pom.xml file:
Maven属性是数值占位符。首先,我们需要在pom.xml文件的properties标签下定义它们。
<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:
然后,我们可以在其他标签中使用它们。例如,在这个例子中,我们将在我们的commons.version依赖中使用”commons-io“值。
<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.
事实上,我们可以在pom.xml的任何地方使用这些属性,例如在build、package或plugin部分。
3. Define Placeholders for Properties
3.定义属性的占位符
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:
有时,我们在开发时不知道某个属性的值。在这种情况下,我们可以使用语法${some_property}留下一个占位符,而不是一个值,Maven会在运行时覆盖占位符的值。让我们为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
4.向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:
现在,让我们像往常一样从终端运行Maven,比如用package命令。但在这种情况下,我们还要在属性名称后面加上符号-D。
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.
Maven将使用作为参数传递的值(2.5)来替换我们的COMMON_VERSION_CMD属性pom.xml中的设置。这并不限于package命令–我们可以在任何Maven命令中一起传递参数,比如install、test或build。
5. Conclusion
5.结论
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.
在这篇文章中,我们研究了如何从命令行向Maven传递参数。通过这种方法,我们不用修改pom.xml或任何静态配置,而可以动态地提供属性。