通过参数配置Mojo,和execute()方法及Mojo注解相比同样重要。本节讲述有关Mojo参数的配置和主题。
在EchoMojo中我们使用如下的注解声明了message参数。
/**
* Any Object to print out.
* @parameter
* expression="${echo.message}"
* default-value="Hello Maven World"
*/
private Object message;
该参数的默认表达式是${echo.message},意思是Maven会使用echo.message属性的值来设置message的值。如果echo.message属性的值是null,@parameter注解的default-value属性就会被使用。除了使用echo.message属性,我们也可以在项目的POM中配置EchoMojo的message参数的值。
有很多中方式可以填充EchoMojo的message参数的值。首先我们可以从命令行传入一个值(假设你已经将org.sonatype.mavenbook.plugins添加到你的pluginGroups中):
$ mvn first:echo -Decho.message="Hello Everybody"
我们也可以通过在POM或者settings.xml中设定一个属性来指定该message参数的值:
<project>
...
<properties>
<echo.message>Hello Everybody</echo.message>
</properties>
</project>
该参数还可以直接通过配置插件来进行配置。如果我们想要直接自定义message参数,我们可以使用如下的build配置。下面的配置绕开了echo.message属性,而是在插件配置中填充Mojo参数:
<project>
...
<build>
<plugins>
<plugin>
<groupId>org.sonatype.mavenbook.plugins</groupId>
<artifactId>first-maven-plugin</artifactId>
<version>1.0-SNAPSHOT</version>
<configuration>
<message>Hello Everybody!</message>
</configuration>
</plugin>
</plugins>
</build>
</project>如果我们想要在一个生命周期的不同阶段中运行EchoMojo两次,并且希望每次运行都能自定义message参数,我们可以在如下在POM中的execution级别配置这个参数值:
<build>
<build>
<plugins>
<plugin>
<groupId>org.sonatype.mavenbook.plugins</groupId>
<artifactId>first-maven-plugin</artifactId>
<version>1.0-SNAPSHOT</version>
<executions>
<execution>
<id>first-execution</id>
<phase>generate-resources</phase>
<goals>
<goal>echo</goal>
</goals>
<configuration>
<message>The Eagle has Landed!</message>
</configuration>
</execution>
<execution>
<id>second-execution</id>
<phase>validate</phase>
<goals>
<goal>echo</goal>
</goals>
<configuration>
<message>0.5</message>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</build>虽然上面的配置样例看起来有些啰嗦,但它展示了Maven的弹性。在前面的配置样例中,我们将EchoMojo同时绑定到了默认Maven生命周期的validate和generate-resources阶段。第一次执行被绑定到了generate-resources,它为message参数提供了字符串值“The
Eagle has
Landed!”。第二次运行则被绑定到了validate阶段,它提供了一个属性引用0.5。当你为该项目运行mvn
install的时候,你会看到first:echo目标执行了两次,并打印了不同的信息。

