Maven:如何在Mojos之间传递参数?

时间:2010-10-31 01:00:18

标签: maven-2 maven-plugin

如何编写一个Mojo来设置另一个Mojo的配置?例如:Mojo A需要定义配置参数A.foo。用户可以手动指定A.foo,也可以运行插件B来计算他/她的值。

3 个答案:

答案 0 :(得分:6)

回答我自己的问题:

可以使用MavenProject实例在运行时访问插件的配置或项目范围的属性:

/**
 * The maven project.
 * 
 * @parameter expression="${project}"
 * @readonly
 */
 private MavenProject project;

然后,您可以在运行时访问插件的配置:

private Plugin lookupPlugin(String key)
{
    List plugins = getProject().getBuildPlugins();

    for (Iterator iterator = plugins.iterator(); iterator.hasNext();)
    {
        Plugin plugin = (Plugin) iterator.next();
        if(key.equalsIgnoreCase(plugin.getKey()))
            return plugin;
    }
    return null;
}

...
Xpp3Dom configuration = (Xpp3Dom) Plugin.getConfiguration()
configuration.getChild("parameterName"); // get parameter
configuration.addChild(new Xpp3Dom("parameterName")); // add parameter
...

注意:在当前阶段结束时,将丢弃任何配置更改。

来源:Best way to access the runtime configuration of a maven plugin from a custom mojo?

或者,您可以使用MavenProject.getProperties()获取/设置项目范围的参数。

答案 1 :(得分:2)

我想maven的方法是在第一个Mojo中设置一个属性并从另一个Mojo访问它。

答案 2 :(得分:2)

这主要是由于Maven运行时“插件配置”的时间安排而导致的。从getBuildPlugins更改“配置”通常不起作用。

如果要编写目标插件,最好的方法是default-value,否则使用属性。

使用属性,但您必须注意如何使用属性。需要注意的是,如果您的POM(或任何父级)定义了属性的值,那么在加载POM时将替换$ {property}引用。但是,如果没有“property”属性,则$ {property}引用将保留,并且仅在最后一刻替换为空值。

“default-value”也会在最后一刻被评估,我认为这是一个更安全的解决方案,因为有一个逻辑上的原因,为什么必须在最后可能的时刻进行评估,其中 - 作为不存在的属性可能只是一个实现细节,可能会在未来的Maven版本中发生变化。

在我的情况下,我不得不诉诸属性,因为我想控制surefire插件的“classesDirectory”。当Cobertura没有运行时,我希望它继续默认为$ {project.build.outputDirectory},但是当Cobertura运行时,我希望它使用$ {project.build.outputDirectory} / generated-classes / cobertura。

在插件部分中定义:

<plugin>
 <groupId>org.apache.maven.plugins</groupId>
 <artifactId>maven-surefire-plugin</artifactId>
 <version>${maven-surefire-plugin.version}</version>
 <configuration>
  <classesDirectory>${instrumentedClassesDirectory}</classesDirectory>
 </configuration>
</plugin>

然后在“源”插件中:

getProject().getProperties().put("instrumentedClassesDirectory", coberturaDir);

并且确保在任何情况下都不会在任何POM中添加以下内容:

<properties>
  <instrumentedClassesDirectory>${project.build.outputDirectory}</instrumentedClassesDirectory>
</properties>

因为如果你这样做,即使你的源插件设置了属性的值,你的目标插件也不会看到该值。如果你使用一个属性传递给源插件的默认值,你可以忽略这最后的警告,但正如我所说的那样,因为我不想改变project.build.outputDirectory的值而无法工作。