Maven之依赖机制

1.  Maven依赖机制作用

    能够自动下载和管理项目所需的外部库(JAR 文件)及其依赖关系。

    Maven 依赖机制极大地简化了 Java 项目的构建过程,使开发者无需手动下载和管理各种第三方库。

    Maven 通过中央仓库(Maven Central Repository)存储了数百万个开源库,当你在项目中声明某个依赖时,Maven 会自动从仓库中下载该库及其所有依赖项。

2.  依赖声明方式

    在 pom.xml 中通过 <dependency> 标签声明    

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
</dependencies>

3.  Maven依赖的基本概念

    1.  坐标系统

        Maven 使用三个基本坐标来唯一标识一个依赖项:

          groupId:定义项目所属的组织或公司(如 org.apache)

          artifactId:定义项目的名称(如 commons-lang3)

          version:定义项目的版本(如 3.12.0)

    2.  依赖范围  

        Maven 定义了不同的依赖范围,决定了依赖在哪些阶段可用:

          compile(默认):编译、测试和运行时都可用

          provided:编译和测试时可用,但运行时由 JDK 或容器提供

          runtime:只在测试和运行时需要

          test:仅在测试编译和执行阶段需要

          system:类似于 provided,但需要显式指定 JAR 路径

    3.  传递性依赖

        当项目 A 依赖项目 B,而项目 B 又依赖项目 C 时,Maven 会自动将项目 C 也作为项目 A 的依赖引入。这种自动处理依赖关系的特性称为传递性依赖。

        传递规则取决于 Scope:

        image

4.  如何使用Maven依赖

    1.  在pom.xml中添加依赖

<dependencies>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>3.12.0</version>
    </dependency>
</dependencies>

    2.  依赖排除

        使用<exclusions>标签

<dependency>
    <groupId>com.example</groupId>
    <artifactId>example-library</artifactId>
    <version>1.0</version>
    <exclusions>
        <exclusion>
            <groupId>org.unwanted</groupId>
            <artifactId>unwanted-dependency</artifactId>
        </exclusion>
    </exclusions>
</dependency>

    3.  依赖管理

        在多模块项目中,可以在父 POM 中使用 <dependencyManagement> 统一管理依赖版本

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.3.20</version>
        </dependency>
    </dependencies>
</dependencyManagement>

5.  Maven依赖解析机制  

    1.  依赖调解

        当出现版本冲突时,Maven使用以下规则解决

          1.  最近定义优先(在依赖树中路径最短的版本被选中)

          2.  如果路径长度相同,则先声明的依赖优先

    2.  依赖范围影响

        不同范围的依赖会影响传递性:

          compile 范围的依赖会传递

          provided 和 test 范围的依赖不会传递

          runtime 范围的依赖会以 runtime 范围传递

        不同Scope的依赖最终打包结果          

          image                          

posted @ 2025-11-26 13:21  奋斗史  阅读(61)  评论(0)    收藏  举报