Search code examples
mavendependenciesdependency-management

Programmatically retrieve all Maven dependencies


How can I in an very easy way retrieve all direct and transitive dependencies for a given Maven POM in my own Java program?

I aware of the existing questions on Stackoverflow, especially the one using Ivy to resolve the dependencies. I am looking for a solution using Maven, which is able also to resolve the transitive dependencies.


Solution

  • I was now able to solve the problem by using JBoss Shrinkwrap.

    Here is a code snipped similar to the one I now use in my tools:

    MavenStrategyStage resolve = 
        Maven.configureResolver()
             // do not consult Maven Central or any other repository
             .workOffline()
             // import the configuration of the given settings.xml
             .fromFile(homeDir + "/jqa-release-environment/maven-settings.xml")
             // load the POM you would like to analyse
             .loadPomFromFile(pomFile)
             .importCompileAndRuntimeDependencies()
             .importRuntimeAndTestDependencies()
             .resolve();
    
    MavenWorkingSession mavenWorkingSession = 
        ((MavenWorkingSessionContainer) resolve).getMavenWorkingSession();
    
    List<MavenDependency> dependencies = new ArrayList<>();
    dependencies.addAll(mavenWorkingSession.getDependenciesForResolution());
    dependencies.addAll(mavenWorkingSession.getDependencyManagement());
    

    To be able to use Shrinkwrap, I added the following dependencies to my POM.

    <dependency>
        <groupId>org.jboss.shrinkwrap.resolver</groupId>
        <artifactId>shrinkwrap-resolver-depchain</artifactId>
        <type>pom</type>
        <version>3.1.4</version>
    </dependency>
    <dependency>
        <groupId>org.jboss.shrinkwrap.resolver</groupId>
        <artifactId>shrinkwrap-resolver-impl-maven</artifactId>
        <version>3.1.4</version>
    </dependency>
    <dependency>
        <groupId>org.jboss.shrinkwrap.resolver</groupId>
        <artifactId>shrinkwrap-resolver-api-maven</artifactId>
        <version>3.1.4</version>
    </dependency>