Find dependencies of a Maven Dependency object

后端 未结 2 950
春和景丽
春和景丽 2021-01-15 09:47

I\'m writing a Maven 3 plugin that needs to know the transitive dependencies of a given org.apache.maven.model.Dependency. How can I do that?

2条回答
  •  青春惊慌失措
    2021-01-15 10:13

    So the following code should give you an impression how to do it.

    @Mojo( name = "test", requiresDependencyResolution = ResolutionScope.COMPILE, defaultPhase = LifecyclePhase.PACKAGE ...)
    public class TestMojo
        extends AbstractMojo
    {
        @Parameter( defaultValue = "${project}", readonly = true )
        private MavenProject project;
    
        public void execute()
            throws MojoExecutionException, MojoFailureException
        {
            List dependencies = project.getDependencies();
            for ( Dependency dependency : dependencies )
            {
                getLog().info( "Dependency: " + getId(dependency) );
            }
    
            Set artifacts = project.getArtifacts();
            for ( Artifact artifact : artifacts )
            {
                getLog().info( "Artifact: " + artifact.getId() );
            }
        }
    
        private String getId(Dependency dep) {
            StringBuilder sb = new StringBuilder();
            sb.append( dep.getGroupId() );
            sb.append( ':' );
            sb.append( dep.getArtifactId() );
            sb.append( ':' );
            sb.append( dep.getVersion() );
            return sb.toString();
        }
    
    }
    

    The above code will give you the resolved artifacts as well as dependencies. You need to make a difference between the dependencies (in this case the project dependencies without transitive and the artifacts which are the solved artifacts incl. transitive.).

    Most important is requiresDependencyResolution = ResolutionScope.COMPILE otherwise you will get null for getArtifacts().

    The suggestion by Tunaki will work for any kind of artifact which is not part of your project...The question is what you really need?

提交回复
热议问题