drJava
drJava

Reputation: 787

How to exclude an artifact, which is used as transitive by several other dependencies, in one place

Our project has migrated from log4j to log4j2. However, other projects, which our project depends on, are still using log4j.
If I want to exclude log4j with exclusions, I need to add more than 10 exclusions on a single pom.xml and it is not practical.

Question: is there any way to say, it does not matter, from where it comes, exclude log4j from my project. It is like the exact opposite of adding dependency.

Upvotes: 1

Views: 916

Answers (1)

A_Di-Matteo
A_Di-Matteo

Reputation: 27812

This not possible at POM level, as stated by official documentation

Why exclusions are made on a per-dependency basis, rather than at the POM level

This is mainly done to be sure the dependency graph is predictable, and to keep inheritance effects from excluding a dependency that should not be excluded. If you get to the method of last resort and have to put in an exclusion, you should be absolutely certain which of your dependencies is bringing in that unwanted transitive dependency.

If you have control over the other projects you depend on, then the concerned dependency should be declared as optional.

<dependency>
    <groupId>com.sample</groupId>
    <artifactId>project</artifactId>
    <version>1.0</version>
    <optional>true</optional>
</dependency>

Optional doesn't affect the project itself (it will keep on having this dependency) but it will not be considered as transitive dependency by dependent projects (hence, you will have the choice to ignore it or to re-declare it, if needed).

As from official documentation

Optional dependencies - If project Y depends on project Z, the owner of project Y can mark project Z as an optional dependency, using the "optional" element. When project X depends on project Y, X will depend only on Y and not on Y's optional dependency Z. The owner of project X may then explicitly add a dependency on Z, at her option. (It may be helpful to think of optional dependencies as "excluded by default.").


Afterwards, if you really want to make sure that the concerned dependency is not brought in by any dependency transitively, you could configure your build to ban it (the build would fail whenever the concerned dependency appears) using the Maven Enforcer Plugin and its bannedDependencies rule.

Upvotes: 3

Related Questions