How to exclude dependency in Gradle projects?

This tutorial talks about how to exclude dependency in Gradle. This post also includes excluding jar files in groovy and kotlin scripts.

Gradle uses two different version syntaxes for configuring build dependencies

  • groovy
  • kotlin

How to exclude transitive dependencies in Gradle?

This section talks about excluding runtime and compile time for each dependency.

exclude runtime dependency: Sometimes, You have transitive dependencies which are causing conflict with the version of the direct dependency.

It excludes the dependency library from the given output jar or the war file.

Suppose org.springframework.security module has a dependency spring-security-web You want to exclude spring-security-web,

You have to configure the Groovy script as follows

implementation('org.springframework.security.spring-security-taglibs:4.3.0') {
        exclude group: 'org.springframework.security', module: 'spring-security-web'
    }

Kotlin

implementation('org.springframework.security.spring-security-taglibs:4.3.0') {
        exclude(group='org.springframework.security', module= 'spring-security-web')
    }

with exclude, It excludes the module by group and module and there is no support for version.

exclude compile dependency: In compile configuration, Add exclude configuration with module and module names to exclude during compile goal.

compile ('org.springframework.security.spring-security-taglibs:4.3.0'){
        exclude group: 'org.springframework.security', module: 'spring-security-web'
}


compile('org.springframework.security.spring-security-taglibs:4.3.0') {
        exclude(group='org.springframework.security', module= 'spring-security-web')
    }

How to exclude dependencies globally in Gradle projects?

Sometimes, We want to exclude global dependencies that are applicable to compile and runtime dependencies.

using configurations.all attributes, You can add exclude option with dependency using group and module

configurations.all {
   exclude group:"org.slf4j", module: "slf4j-api"
}

Conclusion

In this tutorial, You learned how to exclude dependencies globally as well per dependency in compile and runtime dependency.

With Gradle, You can exclude with group and module names only, But not version configuration.