依赖管理

返回构建工具


依赖坐标

Maven/Gradle 通过 GAV 唯一标识一个构件:

groupId:artifactId:version
例:org.springframework.boot:spring-boot-starter-web:3.2.0

Maven 依赖管理

查看 Maven 详细文档

依赖范围(scope)

scope编译测试运行打包说明
compile(默认)最常用
provided容器提供,如 servlet-api
runtime运行时需要,如 JDBC 驱动
test仅测试,如 JUnit

依赖传递与冲突

A → B → C,A 间接依赖 C。

冲突解决规则

  1. 最短路径优先A→B→C:1.0A→C:2.0,选 C:2.0
  2. 声明顺序优先:路径相同时,pom.xml 中先声明的优先

排除传递依赖

<dependency>
    <groupId>com.example</groupId>
    <artifactId>b</artifactId>
    <version>1.0</version>
    <exclusions>
        <exclusion>
            <groupId>com.example</groupId>
            <artifactId>c</artifactId>
        </exclusion>
    </exclusions>
</dependency>

dependencyManagement

在父 pom 中统一声明版本,子模块无需指定版本:

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>3.2.0</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

常用命令

mvn dependency:tree       # 查看完整依赖树
mvn dependency:analyze    # 分析无用/缺失依赖
mvn dependency:resolve    # 解析并下载所有依赖

Gradle 依赖管理

查看 Gradle 详细文档

依赖配置

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-web:3.2.0")
    testImplementation("org.junit.jupiter:junit-jupiter:5.10.0")
    compileOnly("org.projectlombok:lombok:1.18.30")
    annotationProcessor("org.projectlombok:lombok:1.18.30")
    runtimeOnly("com.mysql:mysql-connector-j:8.2.0")
}

配置说明

配置说明
implementation编译+运行,不对外暴露(推荐)
api编译+运行,对外暴露(需 java-library 插件)
compileOnly仅编译,如 Lombok
runtimeOnly仅运行,如数据库驱动
testImplementation仅测试

排除传递依赖

implementation("com.example:b:1.0") {
    exclude(group = "com.example", module = "c")
}

强制指定版本

configurations.all {
    resolutionStrategy {
        force("com.example:c:2.0")
    }
}

常用命令

./gradlew dependencies                                   # 查看依赖树
./gradlew :module:dependencies                           # 指定模块依赖树
./gradlew dependencyInsight --dependency spring-core     # 追踪某个依赖来源

相关文档