Maven dependency exclusion


This article helps you in such cases:

  • Maven doesn’t see exclusion tag
  • dependency exclusion not working in Maven
  • Maven doesn’t see provided scope
  • Maven provided scope not working
  • maven-assembly-plugin not seeing exclusion tag
  • maven-shade-plugin not seeing exclusion tag
  • Maven exclusion not working
  • Maven exclude dependency problem
  • Maven dependency exclusion fix
  • Maven exclude not excluding

There are at least two reasons for such problems.

The first reason

This dependency is transitive for other dependency, not that one, where you made exclusion. Thus, you need to add an exclusion tag somewhere else (if your exclusion is located in a section, not plugin-level).

mvn dependency:tree is invaluable for these searches.


The second reason

These dependency classes come to your jar straight from some dependency artifact as ordinary classes, not transitive dependency.

There is some chance that one of the dependencies of your project represents fat jar. Certain classes which you want to exclude comes to your project as ordinary classes, not transitive dependency. Thus, Maven unable to exclude it. Also, this is a reason that Maven’s provided scope is not working (classes still presented in your jar).

Example number one

For example, you want to get rid of log4j:1.x-specific classes. You made exclusions of log4j-api:1.x and log4j-core:1.x artifacts, but you still see log4j:1.x-specific classes in your jar. The reason may be that you have log4j-1.2-api artifact, which is bridge from log4j 1.x to log4j 2.x. It allows your code to use log4j 1.x classes, and merely redirects all logic to log4j 2.x classes.

Example number two

  • You have your main project_A, which depends on library_B
  • library_B is depending on library_C
  • You want to get rid of library_C

library_B and library_C are always downloaded automatically by Maven every time you compile your project_A, but you once decided that you need to make some changes in library_B. You downloaded source code and made fat jar of library_B. Then you install that fat jar of library_B in your local .m2.

You compile project_A with exclusion tag like this:

<dependency>
    <groupId>org.example</groupId>
    <artifactId>library_B</artifactId>
    <exclusions>
        <exclusion>
            <groupId>com.companty</groupId>
            <artifactId>library_C</artifactId>
        </exclusion>
    </exclusions>
</dependency>

But suddenly it’s not working.

The reason being is that you’ve made library_B as fat jar, when you compiled it by yourself. Hence, classes from library_C comes to your fat jar not as transitive dependency, but as ordinary library_B classes.

You don’t have to compile any library as a fat jar. Thus, made ordinary jar of library_B, whenever you need to make some changes, and Maven’s exclusion going to be working again.