Maven dependency exclusion not working

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

There are at list two reasons of such problems:

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

mvn dependency:tree is very useful for these searches.

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

There is some chance that one of 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 wanna 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 is depending on library_B
  • library_B is depending on library_C
  • You wanna get rid of library_C

library_B & library_C is 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 is because you’ve made library_B as fat jar, when you compiled it by yourself. So 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 fat jar. Thus, made ordinary jar of library_B, whenever you need to make some changes, and Maven’s exclusion gonna be working again.

Telegram channel

If you still have any questions, feel free to ask me in the comments under this article or write me at promark33@gmail.com.

If I saved your day, you can support me 🤝

Leave a Reply

Your email address will not be published. Required fields are marked *