Gradle exclude specific files inside dependency

Solution 1:

I don't think Gradle has any built in support for accomplishing this, but you can clean the artifacts out from the classpath yourself.

Inspired by this thread on the Gradle forums I came up with this:

// The artifacts we don't want, dependency as key and artifacts as values
def unwantedArtifacts = [
    "dep.location:example": [ "foo-1-0-xml", "bar-1-0", "bar-1-0-async", "bar-1-0-xml"],
]

// Collect the files that should be excluded from the classpath
def excludedFiles = configurations.compile.resolvedConfiguration.resolvedArtifacts.findAll {
    def moduleId = it.moduleVersion.id
    def moduleString = "${moduleId.group}:${moduleId.name}:${moduleId.version}" // Construct the dependecy string
    // Get the artifacts (if any) we should remove from this dependency and check if this artifact is in there
    it.name in (unwantedArtifacts.find { key, value -> moduleString.startsWith key }?.value)
}*.file

// Remove the files from the classpath
sourceSets {
    main {
        compileClasspath -= files(excludedFiles)
    }
    test {
        compileClasspath -= files(excludedFiles)
    }
}

Note that Gradle will probably still download the files and cache them for you, but they should not be in your classpath.

Solution 2:

I am not sure if this is what you want, but since we are using Spring Boot and Wildfly, we have to remove the tomcat-starter module from the spring boot standard package, and it looks very similar to what you've done. However, our code states:

configurations {
    compile.exclude module: "spring-boot-starter-tomcat"
}

I have not checked if the corresponding jar is not downloaded or just not on the classpath, I know however that it is not used anymore.