如何在 Maven 中为我的依赖项之一指定特定的依赖项版本

How to specify certain dependency version for one of my dependencies in Maven

我有一个项目使用最新版本的 Hibernate(比如说 v2.0)。我在整个项目中都在使用它。但是我的项目也使用了一些依赖项(比如 MySQL 连接器),它使用 Hibernate(比如 v1.0)。所以在我的 pom.xml 中我会有类似的东西:

<dependencies>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>Hibernate</artifactId>
            <version>2.0</version>
        </dependency>
        <dependency>
            <groupId>org.mysql</groupId>
            <artifactId>MySQLConnector</artifactId>
            <version>3.7</version>
        </dependency>
</dependencies>

最后我编译项目的时候,下载使用的Hibernate版本是v1.0,因为MySQLConnector需要这个。有没有一种方法可以指定某个版本的依赖项,仅供我的一个依赖项使用,而其余代码使用另一个版本?所以像:

<dependencies>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>Hibernate</artifactId>
            <version>2.0</version>
        </dependency>
        <dependency>
            <groupId>org.mysql</groupId>
            <artifactId>MySQLConnector</artifactId>
            <version>3.7</version>
            <somemagicaltag>
               <groupId>org.hibernate</groupId>
               <artifactId>Hibernate</artifactId>
               <version>1.0</version>
            </somemagicaltag>
        </dependency>
</dependencies>

从而允许 MySQLConnector 在它喜欢的情况下使用旧版本的 Hibernate,但我的代码的其余部分使用更新版本的 Hibernate?

您可以跳过下载由 Maven 下载的默认工件。

<dependencies>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>Hibernate</artifactId>
            <version>2.0</version>
        </dependency>
        <dependency>
            <groupId>org.mysql</groupId>
            <artifactId>MySQLConnector</artifactId>
            <version>3.7</version>
            <exclusions>
                <exclusion>  <!-- declare the exclusion here -->
                    <groupId>org.hibernate</groupId>
                    <artifactId>Hibernate</artifact>
                </exclusion>
           </exclusions> 
        </dependency>
</dependencies>
  1. 在所有 "normal" 情况下,您声明的依赖性胜过可传递的依赖性。所以我假设在您的设置中,您获得了 hibernate 的版本 2(没有别的)。调用mvn dependency:list.

  2. 即可知道
  3. 你不能在不同的版本中加载相同的class两次,所以通常情况下,你不能在同一个项目中有两个版本的hibernate。有一些方法可以解决这个问题(使用 Maven 阴影插件),但这应该是个例外。尝试使您自己的代码和您的依赖项与相同版本的休眠一起工作。

Is there a way to specify some version of a dependency that will be used only by one of my dependencies and the rest of the code to use another version?

没有。只可以有一个人。因此,在您的情况下,1.0 或 2.0(通常使用较新的版本更有意义)。使用哪个版本取决于 pom.xml 中使用这种传递依赖的依赖顺序:

您还可以通过指定此类依赖项(这会覆盖传递依赖项版本)或通过在 dependencyManagement 标记中定义此类依赖项来定义将使用哪个版本:Differences between dependencyManagement and dependencies in Maven or by using BOM mechanism: