eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)