1. Overview

Gradle is a build automation tool for managing and automating the process of building, testing, and deploying applications.

Using a domain-specific language (DSL) based on Groovy or Kotlin to define build tasks makes it easy to define and manage the library dependencies needed in a project automatically.

In this tutorial, we’ll specifically discuss several ways to exclude transitive dependencies in Gradle.

2. What Are Transitive Dependencies?

Let’s say we use a library A that depends on another library B. Then B is called a transitive dependency of A. By default, Gradle will automatically add B to our project’s classpath when we include A, so that code from B can also be used in our project, even though we don’t explicitly add it as a dependency.

To make it clearer, let’s use a real example, where we define Google Guava in our project:

dependencies {
    // ...
    implementation 'com.google.guava:guava:31.1-jre'
}

If Google Guava has dependencies with other libraries, then Gradle will automatically include those other libraries.

To see what dependencies we use in a project, we can print them:

./gradlew <module-name>:dependencies

In this case, we use a module called excluding-transitive-dependencies:

./gradlew excluding-transitive-dependencies:dependencies

Let’s see the output:

testRuntimeClasspath - Runtime classpath of source set 'test'.
\--- com.google.guava:guava:31.1-jre
     +--- com.google.guava:failureaccess:1.0.1
     +--- com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava
     +--- com.google.code.findbugs:jsr305:3.0.2
     +--- org.checkerframework:checker-qual:3.12.0
     +--- com.google.errorprone:error_prone_annotations:2.11.0
     \--- com.google.j2objc:j2objc-annotations:1.3

We can see some libraries that we did not explicitly define, but Gradle added them automatically because Google Guava requires them.

However, there are times when we may have good reasons to exclude transitive dependencies.

3. Why Exclude Transitive Dependencies?

Let’s review a few good reasons why we might want to exclude transitive dependencies:

  • Avoiding Security Issues: For example, Firestore Firebase SDK 24.4.0 or Dagger 2.44 have a transitive dependency on Google Guava 31.1-jre, which has a security vulnerability issue.
  • Avoiding Unwanted Dependencies: Some libraries may bring dependencies irrelevant to our application. However, it should be considered wisely and carefully — for example, when we need to exclude transitive dependencies altogether, no matter the version number.
  • Reducing Application Size: By excluding unused transitive dependencies, we can reduce the number of libraries packaged into the application, thereby reducing the size of the output files (JAR, WAR, APK). We can also use tools like ProGuard that significantly reduce the size of the application by removing unused code, optimizing bytecode, obfuscating class and method names, and removing unnecessary resources. This process results in a smaller, faster, and more efficient application without sacrificing functionality.

So, Gradle also provides a mechanism to exclude dependencies.

3.1. Resolving Version Conflicts

We do not recommend excluding transitive dependencies to resolve version conflicts because Gradle already has a good mechanism to handle that.

When there are two or more identical dependencies, Gradle will only pick one. If they have different versions, by default, it will choose the latest version. This behavior is shown in the logs if we look closely:

+--- org.hibernate.orm:hibernate-core:7.0.0.Beta1
|    +--- jakarta.persistence:jakarta.persistence-api:3.2.0-M2
|    +--- jakarta.transaction:jakarta.transaction-api:2.0.1
|    +--- org.jboss.logging:jboss-logging:3.5.0.Final <-------------------+ same version
|    +--- org.hibernate.models:hibernate-models:0.8.6                     |
|    |    +--- io.smallrye:jandex:3.1.2 -> 3.2.0    <------------------+  |
|    |    \--- org.jboss.logging:jboss-logging:3.5.0.Final +-----------|--+
|    +--- io.smallrye:jandex:3.2.0     +-------------------------------+ latest version
|    +--- com.fasterxml:classmate:1.5.1
|    |    \--- jakarta.activation:jakarta.activation-api:2.1.0 -> 2.1.1 <---+
|    +--- org.glassfish.jaxb:jaxb-runtime:4.0.2                             |
|    |    \--- org.glassfish.jaxb:jaxb-core:4.0.2                           |
|    |         +--- jakarta.xml.bind:jakarta.xml.bind-api:4.0.0 (*)         |
|    |         +--- jakarta.activation:jakarta.activation-api:2.1.1   +-----+ latest version
|    |         +--- org.eclipse.angus:angus-activation:2.0.0                

We can see some of the identified dependencies are the same. For example, org.jboss.logging:jboss-logging:3.5.0.Final appears twice, but since they are the same version, Gradle will only include one copy.

Meanwhile, for jakarta.activation:jakarta.activation-api, two versions are found — 2.1.0 and 2.1.1. Gradle will choose the latest version, which is 2.1.1. The same goes for io.smallrye:jandex, where it will choose 3.2.0.

But there are times when we don’t want to use the latest version. We can force Gradle to choose a version that we need strictly:

implementation("io.smallrye:jandex") {
    version {
        strictly '3.1.2'
    }
}

Here, even if another, even newer version is found, Gradle will still choose version 3.1.2.

We can declare dependencies with specific versions or version ranges to define the acceptable versions of a dependency that our project can use.

4. Excluding Transitive Dependencies

We can exclude transitive dependencies in various scenarios. Well, to make it clearer and easier to understand, we’ll use real examples with libraries that we may be familiar with.

4.1. Excluding Groups

When we define a dependency, for example, Google Guava, if we look, the dependency has a format like this:

com.google.guava : guava : 31.1-jre
----------------   -----   --------
        ^            ^        ^
        |            |        |
      group        module   version

If we look at the output in Section 2, we’ll see five modules that Google Guava depends on. They are com.google.code.findbugs, com.google.errorprone, com.google.guava, com.google.j2objc, and org.checkerframework.

We’ll exclude the com.google.guava group, which contains the guava, failureaccess, and listenablefuture modules:

dependencies {
    // ...
    implementation ('com.google.guava:guava:31.1-jre') {
        exclude group: 'com.google.guava'
    }
}

This will exclude all modules in the com.google.guava group except guava, as it is a main module.

4.2. Excluding Specific Modules

To exclude specific module dependencies, we can use the targeted path. For example, when we use the Hibernate library, we only need to exclude the org.glassfish.jaxb:txw2 module:

dependencies {
    // ...
    implementation ('org.hibernate.orm:hibernate-core:7.0.0.Beta1') {
        exclude group: 'org.glassfish.jaxb', module : 'txw2'
    }
}

This means that even though Hibernate has a dependency on the txw2 module, we’ll not include this module in the project.

4.3. Excluding Multiple Modules

Gradle also allows us to exclude multiple modules in a single dependency statement:

dependencies {
    // ...
    testImplementation platform('org.junit:junit-bom:5.10.0')
    testImplementation ('org.junit.jupiter:junit-jupiter') {
        exclude group: 'org.junit.jupiter', module : 'junit-jupiter-api'
        exclude group: 'org.junit.jupiter', module : 'junit-jupiter-params'
        exclude group: 'org.junit.jupiter', module : 'junit-jupiter-engine'
    }
}

In this example, we exclude the junit-jupiter-api, junit-jupiter-params, and junit-jupiter-engine modules from the org.junit-jupiter dependencies.

With this mechanism, we can do the same thing for more module exclusion cases:

dependencies {
    // ...
    implementation('com.google.android.gms:play-services-mlkit-face-detection:17.1.0') {
        exclude group: 'androidx.annotation', module: 'annotation'
        exclude group: 'android.support.v4', module: 'core'
        exclude group: 'androidx.arch.core', module: 'core'
        exclude group: 'androidx.collection', module: 'collection'
        exclude group: 'androidx.coordinatorlayout', module: 'coordinatorlayout'
        exclude group: 'androidx.core', module: 'core'
        exclude group: 'androidx.viewpager', module: 'viewpager'
        exclude group: 'androidx.print', module: 'print'
        exclude group: 'androidx.localbroadcastmanager', module: 'localbroadcastmanager'
        exclude group: 'androidx.loader', module: 'loader'
        exclude group: 'androidx.lifecycle', module: 'lifecycle-viewmodel'
        exclude group: 'androidx.lifecycle', module: 'lifecycle-livedata'
        exclude group: 'androidx.lifecycle', module: 'lifecycle-common'
        exclude group: 'androidx.fragment', module: 'fragment'
        exclude group: 'androidx.drawerlayout', module: 'drawerlayout'
        exclude group: 'androidx.legacy.content', module: 'legacy-support-core-utils'
        exclude group: 'androidx.cursoradapter', module: 'cursoradapter'
        exclude group: 'androidx.customview', module: 'customview'
        exclude group: 'androidx.documentfile.provider', module: 'documentfile'
        exclude group: 'androidx.interpolator', module: 'interpolator'
        exclude group: 'androidx.exifinterface', module: 'exifinterface'
    }
}

This example excludes various modules from the Google ML Kit dependencies to avoid including certain modules that are already included in the project by default.

4.4. Excluding All Transitive Modules

There may be times when we need to use only the main module without any other dependencies. Or maybe when we need to explicitly specify the version of each dependency used.

The transitive = false statement will tell Gradle not to automatically include transitive dependencies from the libraries we use:

dependencies {
    // ...
    implementation('org.hibernate.orm:hibernate-core:7.0.0.Beta1') {
        transitive = false
    }
}

This means that only Hibernate Core itself will be added to the project, without any other dependencies.

4.5. Exclude From Each Configuration

Besides excluding transitive dependencies in the dependency declaration, we can also do so at the configuration level.

We can use configurations.configureEach { } which configures each element in the collection using the given action.

This method is available in Gradle 4.9 and above as a recommended alternative to all().

Let’s try it right away:

dependencies { 
    // ...
    testImplementation 'org.mockito:mockito-core:3.+'
}

configurations.configureEach {
    exclude group: 'net.bytebuddy', module: 'byte-buddy-agent'
}

This means that we exclude the byte-buddy-agent module of the net.bytebuddy group from all configurations that use that dependency.

4.6. Exclude in Specific Configurations

There may be times when we need to exclude dependencies by targeting a specific configuration. Of course, Gradle allows this, too:

configurations.testImplementation {
    exclude group: 'org.junit.jupiter', module : 'junit-jupiter-engine'
}

configurations.testCompileClasspath {
    exclude group : 'com.google.j2objc', module : 'j2objc-annotations'
}

configurations.annotationProcessor {
    exclude group: 'com.google.guava'
}

Yes, Gradle allows excluding dependencies in this way. We can use exclude in the classpath for specific configurations like testImplementation, testCompileClasspath, annotationProcessor, and others.

5. Conclusion

There are three main reasons to exclude transitive dependencies: avoiding security issues, avoiding libraries that we don’t need, and reducing application size.

In this article, we discussed ways to exclude transitive dependencies in Gradle, starting from excluding by group, specific module, or multiple modules, to excluding all transitive modules. We can also make exclusions at the configuration level. However, exclusions must be considered wisely and carefully.

As always, the full source code is available over on GitHub.