如何让 Maven 构建在重复依赖项上失败?

How can I get a maven build to fail on duplicate dependencies?

如果我在同一个 pom 中有两个相同的依赖项,我希望构建失败。目前我可以通过 Maven 依赖插件 "analyze-duplicate" 检测到它的发生。但是,没有像其他一些选项那样的 failOnWarning 选项(另外,它在信息级别打印,而不是警告)。除了扩展它还有其他选择吗?

通常,当您希望构建由于某种原因失败时,可以查看 Maven Enforcer Plugin 的好插件。这个插件可以配置一组规则,当验证时,构建将失败。

在这种情况下,它需要一个检查重复依赖项的规则,并且有一个专门用于此的内置规则:<banDuplicatePomDependencyVersions>。因此,您可以

<plugin>
  <artifactId>maven-enforcer-plugin</artifactId>
  <version>1.4.1</version>
  <executions>
    <execution>
      <id>enforce-no-duplicate-dependencies</id>
      <goals>
        <goal>enforce</goal>
      </goals>
      <configuration>
        <rules>
          <banDuplicatePomDependencyVersions/>
        </rules>
      </configuration>
    </execution>
  </executions>
</plugin>

不幸的是,这条规则没有记录(但是,它将在下一个版本中,参见 MENFORCER-259), but it exists since version 1.3 of the plugin (MENFORCER-152)。

此规则的作用是检查是否没有 2 个重复声明具有相同的 'dependencies.dependency.(groupId:artifactId:type:classifier)';也就是说,在 POM 中声明的具有相同组 ID 和工件 ID 的两个声明的依赖项必须具有不同的类型 and/or 分类器。