出现依赖冲突时如何中断 Maven 构建?

出现依赖冲突时如何中断 Maven 构建?

问题描述:

我为一个项目运行了 mvn dependency:tree,我看到如下输出:

I ran mvn dependency:tree for a project and I saw output like the following:

[INFO] my:project:jar:1.0.0-SNAPSHOT
[INFO] +- some.other:library:jar:2.0.0:compile
[INFO] |  - org.slf4j:slf4j-api:jar:1.6.1:compile
[INFO] +- org.slf4j:slf4j-simple:jar:1.6.0:compile
[INFO] |  - (org.slf4j:slf4j-api:jar:1.6.0:compile - omitted for conflict with 1.6.1)

这是一个糟糕的状态,因为我的项目直接依赖于 slf4j 1.6.0,而我们依赖的一些库又依赖于 slf4j 1.6.1.这两个版本恰好是二进制兼容的,因此构建通过而没有任何警告.有没有办法让 Maven 对其依赖解析更加严格,以便我可以配置在这种情况下会失败的新构建?在这种情况下,解决方案是将我们的依赖项更新到较新版本的 slf4j.

This is a bad state to be in because my project depends directly on slf4j 1.6.0 and some library that we depend on transitively depends on slf4j 1.6.1. These two versions happen to be binary compatible so the build passes without any warnings. Is there a way to get Maven to be more strict about its dependency resolution so that I could configure a new build that would fail in this scenario? In this case, the solution would be to just update our dependency to the newer version of slf4j.

maven-enforcer-plugin 有一个 dependencyConvergence 配置可以满足我的需求.巧合的是,文档中的示例使用了 slf4j.

The maven-enforcer-plugin has a dependencyConvergence configuration which does what I want. Coincidentally, the example from the documentation uses slf4j.

这样配置:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-enforcer-plugin</artifactId>
    <version>1.0</version>
    <executions>
        <execution>
            <id>enforce</id>
            <configuration>
                <rules> 
                    <DependencyConvergence />
                </rules>
            </configuration>
            <goals> 
                <goal>enforce</goal>
            </goals>
        </execution>
    </executions>
</plugin>

这种依赖组合会导致构建失败:

This combination of dependencies will cause a build to fail:

  <dependencies>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-jdk14</artifactId>
      <version>1.6.1</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-nop</artifactId>
      <version>1.6.0</version>
    </dependency>
  </dependencies>  

在编译期间记录:

[ERROR]
Dependency convergence error for org.slf4j:slf4j-api:1.6.1 paths to dependency are:
+-org.myorg:my-project:1.0.0-SNAPSHOT
  +-org.slf4j:slf4j-jdk14:1.6.1
    +-org.slf4j:slf4j-api:1.6.1
and
+-org.myorg:my-project:1.0.0-SNAPSHOT
  +-org.slf4j:slf4j-nop:1.6.0
    +-org.slf4j:slf4j-api:1.6.0