代码之家  ›  专栏  ›  技术社区  ›  javamonkey79

在maven插件中获取mojo参数

  •  1
  • javamonkey79  · 技术社区  · 6 年前

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

    我有一个基本的魔咒,它有一些特性,比如:

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

    然后,子mojo添加一些附加属性。我希望能够阅读所有这些属性,以验证它们,但不清楚如何这样做。当我使用debug运行它时,我看到:

    [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 回复  |  直到 6 年前
        1
  •  1
  •   javamonkey79    6 年前

    好吧,经过多次调试,我能够根据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();
            }
        }