从一个"meta mojo"执行多个魔术和参数共享



我创建了一个带有一些mojos的maven插件,每个插件都有一个非常特殊的目的。但是对于最终用户来说,最好一次执行其中一些(顺序至关重要)。

那么如何从魔术执行中执行其他魔力呢?被处决的魔术有一些@Parameter领域。所以我不能简单地new MyMojo().execute.

我的第二个问题是:有没有办法在Mojos之间共享一些@Parameters,或者我必须在使用它们的每个Mojo中声明"@Parameter"?我的想法是通过为getter提供参数的实用程序类以某种方式交付所有共享参数。

我认为这两个问题的答案在某种程度上在于理解 maven-mojos 背后的 DI 机制?!我对Guice有一些经验,但对Plexus没有经验。那么有人可以给我一些建议吗?

我不知道

你的第二个问题到底是什么意思。也许他们并没有真正的关系。但我试着从第一个开始回答这两个问题。

问题1:如何从另一个目标调用目标?

为此,您可以使用Apache Maven Invoker。

  1. 将 Maven 依赖项添加到您的插件中。
    例如:

    <dependency>
        <groupId>org.apache.maven.shared</groupId>
        <artifactId>maven-invoker</artifactId>
        <version>2.2</version>
    </dependency>
    
  2. 然后你可以这样称呼另一个目标:

    // parameters:
    final Properties properties = new Properties();
    properties.setProperty("example.param.one", exampleValueOne);
    // prepare the execution:
    final InvocationRequest invocationRequest = new DefaultInvocationRequest();
    invocationRequest.setPomFile(new File(pom)); // pom could be an injected field annotated with '@Parameter(defaultValue = "${basedir}/pom.xml")' if you want to use the same pom for the second goal
    invocationRequest.setGoals(Collections.singletonList("second-plugin:example-goal"));
    invocationRequest.setProperties(properties);
    // configure logging:
    final Invoker invoker = new DefaultInvoker();
    invoker.setOutputHandler(new LogOutputHandler(getLog())); // using getLog() here redirects all log output directly to the current console
    // execute:
    final InvocationResult invocationResult = invoker.execute(invocationRequest);
    

问题 2:如何在 mojos 之间共享参数?

你的意思是:

  1. 如何在一个插件内的多个目标之间共享参数?
    (见"对问题2.1的回答")
  2. 如何为执行的"子魔术"重用"元魔术"的参数?
    (见"对问题2.2的回答")

对问题2.1的回答:

您可以创建一个包含参数字段的抽象父类。

例:

abstract class AbstractMyPluginMojo extends Abstract Mojo {
    @Parameter(required = true)
    private String someParam;
    protected String getSomeParam() {
        return someParam;
    }
}
@Mojo(name = "first-mojo")
public class MyFirstMojo extends AbstractMyPluginMojo {
    public final void execute() {
        getLog().info("someParam: " + getSomeParam());
    }
}
@Mojo(name = "second-mojo")
public class MySecondMojo extends AbstractMyPluginMojo {
    public final void execute() {
        getLog().info("someParam: " + getSomeParam());
    }
}

您可以在几乎一个非常大的 maven 插件中找到这种技术。例如,查看Apache Maven插件源代码。

对问题2.2的回答:

您可以在我对问题 1 的回答中对此进行解决方案。如果你想在你的"meta mojo"中执行多个目标,你可以重用properties变量。

最新更新