用于获取Maven依赖关系图的Java代码

时间:2015-06-17 15:18:11

标签: java eclipse maven dependencies aether

我正在处理的程序的一个要求是我需要能够查看存储库中几个工件的Maven依赖关系,以便我可以为它们创建依赖关系图。虽然Maven和Eclipse Aether很明显可以做到这一点(因为Maven的很大一部分是依赖关系),但我很难确定如何在Java程序中完成它。

有什么建议吗?

3 个答案:

答案 0 :(得分:1)

根据{{​​3}},似乎以太可以提供帮助。甚至有documentation。将其与an example that demonstrates how to use Aether to collect the transitive dependencies of an artifact相结合,我认为你可以得到你想要的地方。

答案 1 :(得分:0)

实现这一目标的几种方法是使用像Eclipse这样的IDE ......或者你可以使用maven-dependency-plugin打印到控制台......

mvn dependency:tree

答案 2 :(得分:0)

在查看各种不同的示例和代码之后,我拼凑了这个,这似乎有效:

public List<Artifact> fetchArtifactDependencies(final RepositorySystemSession session,
                                                final Artifact artifact,
                                                final DependencyFilter dependencyFilter)
        throws RepositoryException {

    final CollectRequest collectRequest = new CollectRequest();
    collectRequest.setRoot(new Dependency(artifact, "compile"));
    collectRequest.addRepository([repository]);

    final DependencyNode node = repositorySystem.collectDependencies(session, collectRequest)
                                                .getRoot();

    final DependencyRequest dependencyRequest = new DependencyRequest();
    dependencyRequest.setRoot(node);
    dependencyRequest.setFilter(dependencyFilter);

    final DependencyResult dependencyResult = repositorySystem.resolveDependencies(session,
                                                                                   dependencyRequest);

    final List<ArtifactResult> artifactResults = dependencyResult.getArtifactResults();

    final List<Artifact> results = new ArrayList<>(artifactResults.size());

    CollectionUtils.collect(artifactResults, new Transformer<ArtifactResult, Artifact>() {
        @Override
        public Artifact transform(final ArtifactResult input) {
            return input.getArtifact();
        }
    }, results);

    return results;
}