如何在插件中访问Maven的依赖关系层次结构 [英] How to get access to Maven's dependency hierarchy within a plugin

查看:212
本文介绍了如何在插件中访问Maven的依赖关系层次结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的插件中,我需要处理依赖关系层次结构,并获取有关每个依赖关系以及是否被排除的信息(groupId,artifactId,版本等).最好的方法是什么?

In my plugin I need to process the dependency hierarchy and get information (groupId, artifactId, version etc) about each dependency and if it was excluded. What is the best way to do this?

推荐答案

依赖插件具有

The dependency plugin has the tree goal that does most of this work. It processes a MavenProject using the DependencyTreeBuilder, this returns a DependencyNode with hierarchical information about the resolved dependencies (and their transitive dependencies).

您可以直接从TreeMojo复制许多代码.它使用CollectingDependencyNodeVisitor遍历树并生成所有节点的List.

You can copy much of the code directly from the TreeMojo. It uses the CollectingDependencyNodeVisitor to traverse the tree and produce a List of all the nodes.

您可以通过调用getArtifact()来访问节点的Artifact,然后根据需要获取工件信息.为了获得排除原因,DependencyNode有一个getState()方法,该方法返回一个int,指示是否已包含依赖项,或者是否省略了依赖项的原因(DependencyNode类中有常量检查返回值)反对)

You can access the Artifact for the node by calling getArtifact(), then get the artifact information as needed. To get the exclusion reason, DependencyNode has a getState() method that returns an int indicating if the dependency has been included, or if not what the reason for omitting it was (there are constants in the DependencyNode class to check the return value against)

//All components need this annotation, omitted for brevity

/**
 * @component
 * @required
 * @readonly
 */
private ArtifactFactory artifactFactory;
private ArtifactMetadataSource artifactMetadataSource;
private ArtifactCollector artifactCollector;
private DependencyTreeBuilder treeBuilder;
private ArtifactRepository localRepository;
private MavenProject project;

public void execute() throws MojoExecutionException, MojoFailureException {
    try {
        ArtifactFilter artifactFilter = new ScopeArtifactFilter(null);

        DependencyNode rootNode = treeBuilder.buildDependencyTree(project,
                localRepository, artifactFactory, artifactMetadataSource,
                artifactFilter, artifactCollector);

        CollectingDependencyNodeVisitor visitor = 
            new CollectingDependencyNodeVisitor();

        rootNode.accept(visitor);

        List<DependencyNode> nodes = visitor.getNodes();
        for (DependencyNode dependencyNode : nodes) {
            int state = dependencyNode.getState();
            Artifact artifact = dependencyNode.getArtifact();
            if(state == DependencyNode.INCLUDED) {                    
                //...
            } 
        }
    } catch (DependencyTreeBuilderException e) {
        // TODO handle exception
        e.printStackTrace();
    }
}

这篇关于如何在插件中访问Maven的依赖关系层次结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆