The solution here is for Maven. For using Gradle 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 you have the following dependency:
<dependencies> <dependency> <groupId>net.maxjava</groupId> <artifactId>MyFoo</artifactId> <version>1.0</version> </dependency> </dependencies>
And let say you want to exclude the mypackage.Myunwanted class of MyFoo, what you need is creating a wrapper jar and use maven-shade-plugin 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 section to the pom:
<dependencies> <dependency> <groupId>net.maxjava</groupId> <artifactId>MyFoo</artifactId> <version>1.0</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>3.2.1</version> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> <filters> <filter> <artifact>net.maxjava:MyFoo</artifact> <excludes> <exclude>mypackage/UnwantedClass.class</exclude> </excludes> </filter> </filters> </configuration> </execution> </executions> </plugin> </plugins> </build>
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> <dependency> <groupId>net.maxjava</groupId> <artifactId>MyFooWrapper</artifactId> <version>1.0</version> <exclusions> <exclusion> <groupId>net.maxjava</groupId> <artifactId>MyFoo</artifactId> </exclusion> </exclusions> </dependency> </dependencies>
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