如何在一个地方排除被其他几个依赖项用作传递的工件

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

我们的项目已从 log4j 迁移到 log4j2。但是我们项目依赖的其他项目还在使用log4j.
如果我想用 exclusions 排除 log4j,我需要在单个 pom.xml 上添加超过 10 个排除项,这是不切实际的。

问题:有没有办法说,没关系,从哪里来,把log4j排除在我的项目之外。它就像添加依赖项的相反。

这在 POM 级别是不可能的,如 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.

如果您可以控制您所依赖的其他项目,则相关依赖项应声明为optional

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

Optional 不影响项目本身(它会一直有这个依赖)但是它不会被依赖项目认为是传递依赖(因此,你可以选择忽略它或重新声明它,如果需要的话)。

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.").


之后,如果您真的想确保相关依赖项不是由任何依赖项传递引入的,您可以将构建配置为禁止它(只要相关依赖项出现,构建就会失败)使用 Maven Enforcer Plugin and its bannedDependencies规则。