Home > Mobile >  How do I get the direct (non transitive) dependencies of a Maven project?
How do I get the direct (non transitive) dependencies of a Maven project?

Time:10-12

Currently, when processing a MavenProject, I'm using getDependencyArtifacts to fetch the direct (non transitive) dependencies. However, this method is marked as deprecated. So, what am I supposed to use as a replacement ? I see there's the method getDependencies, but it fetches transitive dependencies, and I don't see any way to filter direct dependencies.

Am I supposed to use RepositorySystem, and its method collectDependencies, and navigate the resulting graph, and get only the children of the root, which I guess would effectively be the direct dependencies ? Don't I have more direct, non deprecated approaches ?

CodePudding user response:

This is based on a quick search, there is an existing API called Aether. Its documentation is not great.

The method in it is called: getDependencies() and it retrieves direct dependencies according to the javadoc.

https://maven.apache.org/resolver/maven-resolver-api/apidocs/org/eclipse/aether/resolution/ArtifactDescriptorResult.html

There is an example on github:

public class GetDirectDependencies
{

    public static void main( String[] args )
        throws Exception
    {
        System.out.println( "------------------------------------------------------------" );
        System.out.println( GetDirectDependencies.class.getSimpleName() );

        RepositorySystem system = Booter.newRepositorySystem();

        RepositorySystemSession session = Booter.newRepositorySystemSession( system );

        Artifact artifact = new DefaultArtifact( "org.eclipse.aether:aether-impl:1.0.0.v20140518" );

        ArtifactDescriptorRequest descriptorRequest = new ArtifactDescriptorRequest();
        descriptorRequest.setArtifact( artifact );
        descriptorRequest.setRepositories( Booter.newRepositories( system, session ) );

        ArtifactDescriptorResult descriptorResult = system.readArtifactDescriptor( session, descriptorRequest );

        for ( Dependency dependency : descriptorResult.getDependencies() )
        {
            System.out.println( dependency );
        }
    }

}

https://github.com/1984shekhar/fuse-examples-6.2/blob/master/aether-demo-snippets/src/main/java/org/eclipse/aether/examples/GetDirectDependencies.java

  • Related