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

从自定义mojo访问maven插件运行时配置的最佳方法?

  •  15
  • npellow  · 技术社区  · 16 年前

    我正在写一个定制的魔咒。我需要从这个mojo访问另一个插件的运行时配置。

    最好的方法是什么?

    3 回复  |  直到 15 年前
        1
  •  4
  •   Kingamajick    15 年前

    您可以使用以下步骤获取当前在生成中使用的插件列表:

    首先,您需要让maven将当前项目注入到您的mojo中,然后使用下面定义的类变量来获得这个结果。

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

    然后,您可以使用以下命令获取此生成中使用的插件列表。

    mavenProject.getBuildPlugins()
    

    您可以遍历此列表,直到找到要从中提取配置的插件。

    最后,您可以将配置作为xpp3dom。

    plugin.getConfiguration()
    

    注意:如果您改变了其他插件的配置(而不仅仅是提取信息),那么它将只在当前阶段而不是后续阶段保持更改。

        2
  •  3
  •   npellow    16 年前

    使用属性当然是一种方法,但并不理想。它仍然需要用户在pom中的多个位置定义${propertyname}。我想允许我的插件在不修改用户pom的情况下工作,除了插件定义本身。

    我不认为访问另一个mojo的运行时属性是过于紧密的耦合。如果在构建层次结构的任何地方定义了另一个mojo,我希望我的mojo尊重相同的配置。

    我目前的解决方案是:

    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;
    }
    
    
    /**
     * Extracts nested values from the given config object into a List.
     * 
     * @param childname the name of the first subelement that contains the list
     * @param config the actual config object
     */
    private List extractNestedStrings(String childname, Xpp3Dom config) {
    
        final Xpp3Dom subelement = config.getChild(childname);
        if (subelement != null) {
            List result = new LinkedList();
            final Xpp3Dom[] children = subelement.getChildren();
            for (int i = 0; i < children.length; i++) {
                final Xpp3Dom child = children[i];
                result.add(child.getValue());
            }
            getLog().info("Extracted strings: " + result);
            return result;
        }
    
        return null;
    }
    

    这对我测试过的少数几个小版本都有效。包括多模块构建。

        3
  •  0
  •   Mike Deck    16 年前

    我不知道你会怎么做,但在我看来,这可能不是最好的设计决定。如果可能的话,你应该把你的mojo从其他插件中分离出来。

    相反,我建议使用自定义属性来排除单独插件配置中的任何重复。

    您可以使用properties部分在POM中设置自定义属性“foo”:

    <project>
      ...
      <properties>
        <foo>value</foo>
      </properties>
      ...
    </project>
    

    属性foo现在可以在pom中的任何位置使用美元符号+花括号符号进行访问:

    <somePluginProperty>${foo}</somePluginProperty>