在maven插件中获取mojo参数

时间:2018-06-12 18:30:08

标签: java maven maven-3

有没有办法在执行方法中访问插件属性?

我有一个基础mojo,它有一些属性,如:

@Parameter(defaultValue = "DEV", property = "dbEnvironment", required = true)
protected Environment dbEnvironment;

@Parameter(defaultValue = "true", property = "validate")
protected boolean validate;

然后,孩子mojo会添加一些额外的属性。我希望能够阅读所有这些属性,以验证它们,但是如何做到这一点并不明显。当我运行它时,通过调试,我看到了:

[DEBUG] Configuring mojo 'com.company.tools:something-maven-plugin:0.2.11-SNAPSHOT:export-job' with basic configurator -->
[DEBUG]   (f) dbEnvironment = DEV
[DEBUG]   (f) jobName = scrape_extract
[DEBUG]   (f) project = MavenProject: com.company.tools:something-maven-plugin-it:1.0-SNAPSHOT @ /Users/selliott/intellij-workspace/tools-something-maven-plugin/something-maven-plugin/src/it/simple-it/pom.xml
[DEBUG]   (f) session = org.apache.maven.execution.MavenSession@3fd2322d
[DEBUG]   (f) validate = true
[DEBUG] -- end configuration --

所以,看起来这些道具在哪里,但在哪里?我试过从会话中获取它们,session.settings,session.request无济于事。

1 个答案:

答案 0 :(得分:1)

好的,经过大量调试后,我能够根据AbstractConfigurationConverter的工作原理,特别是fromExpression方法来解决这个问题。

要获取属性,您需要在mojo中添加以下内容:

@Parameter(defaultValue = "${session}")
protected MavenSession session;

@Parameter(defaultValue = "${mojoExecution}")
protected MojoExecution mojoExecution;

从那里,你现在可以创建一个评估器和配置(也许你可以直接注入它们,我不确定),你可以这样做:

    PluginParameterExpressionEvaluator expressionEvaluator = new PluginParameterExpressionEvaluator(session, mojoExecution);
    PlexusConfiguration pomConfiguration = new XmlPlexusConfiguration(mojoExecution.getConfiguration());

    for (PlexusConfiguration plexusConfiguration : pomConfiguration.getChildren()) {
        String value = plexusConfiguration.getValue();
        String defaultValue = plexusConfiguration.getAttribute("default-value");
        try {
            String evaluated = defaultIfNull(expressionEvaluator.evaluate(defaultIfBlank(value, defaultValue)), "").toString();
            System.out.println(plexusConfiguration.getName() + " -> " + defaultIfBlank(evaluated, defaultValue));
        } catch (ExpressionEvaluationException e) {
            e.printStackTrace();
        }
    }