Exclude a particular class from a jar inside a war file using Gradle. This could be due to multiple versions of a library are included and we want to avoid the application to load the unwanted version but we don't want to exclude the whole jar.

Configuration
Java Compilation:
Java Runtime:
Gradle:
JDK 11.0.12
JRE HotSpot 11.0.12
Gradle 7.4.2
The solution here is for Gradle. For using Maven please visit
Sometimes we want to exclude a particular class from a jar inside a war file
This could be due to multiple versions of a library are included and we want to avoid the application to load the unwanted version but we don't want to exclude the whole jar
Assuming we have the following dependency:
dependencies { implementation group: 'net.maxjava', name: 'MyFoo', version: '1.0' }
And let say we want to exclude the mypackage.Myunwanted class of MyFoo, what we need is creating a wrapper jar and use com.github.johnrengelman.shadow to exclude the class. After that just make the war use the wrapper jar instead
Create a wrapper jar named MyFooWrapper and add the following to build.gradle:
plugins { id 'java' id 'com.github.johnrengelman.shadow' version "7.1.2" id 'maven-publish' } repositories { mavenLocal() mavenCentral() } group 'net.maxjava' version '1.0' publishing { publications { mavenJava(MavenPublication) { from components.java } } } shadowJar { archiveFileName = "MyFooWrapper-${parent.version}.jar" } dependencies { implementation project(':MyFoo') } shadowJar { exclude "mypackage/UnwantedClass.class" }
To make the wrapper jar available, we can make use of the local repository. So run the following gradle command:
gradle publishToMavenLocal
Now in the war project, reference the wrapper jar just like normal dependency, but make sure to exclude the original jar (MyFoo here)
Otherwise, since dependency is transitive, the original jar thus the mypackage.UnwantedClass class will be included:
dependencies { implementation('net.maxjava:MyFooWrapper:1.0') { exclude group: 'net.maxjava', module: 'MyFoo' } }
Then just build the war normally, the wrapper jar which has all the classes except for mypackage.UnwantedClass from the original jar will be included