Skip to content

依赖管理基础

依赖管理是 Gradle 最核心的功能之一,负责自动下载和管理项目所需的第三方库。

基本概念

dependencies {
    implementation("com.google.guava:guava:32.0.1-jre")
                   └────────────────────────────────────┘
                   group:artifact:version(GAV 坐标)
}
部分说明示例
group组织/公司标识com.google.guava
artifact库名称guava
version版本号32.0.1-jre

依赖配置(Scope)

不同的依赖配置决定了依赖在哪些阶段可用:

kotlin
dependencies {
    // 编译 + 运行时,不传递给消费者(最常用)
    implementation("org.springframework.boot:spring-boot-starter-web:3.2.0")
    
    // 编译 + 运行时,传递给消费者(用于库项目)
    api("org.slf4j:slf4j-api:2.0.9")
    
    // 仅编译时(Lombok、注解处理器、Servlet API 等)
    compileOnly("org.projectlombok:lombok:1.18.30")
    
    // 仅运行时(数据库驱动、日志实现等)
    runtimeOnly("com.mysql:mysql-connector-j:8.2.0")
    
    // 仅测试编译时
    testCompileOnly("org.mockito:mockito-core:5.8.0")
    
    // 测试编译 + 运行时
    testImplementation("org.springframework.boot:spring-boot-starter-test:3.2.0")
    
    // 仅测试运行时
    testRuntimeOnly("org.junit.platform:junit-platform-launcher:1.10.1")
    
    // 注解处理器
    annotationProcessor("org.projectlombok:lombok:1.18.30")
}

传递依赖

当你依赖 A,而 A 又依赖 B 时,B 就是传递依赖(间接依赖)。Gradle 自动处理传递依赖。

bash
# 查看完整依赖树(含传递依赖)
./gradlew dependencies --configuration compileClasspath

# 输出示例:
# compileClasspath - Compile classpath for source set 'main'.
# +--- org.springframework.boot:spring-boot-starter-web:3.2.0
# |    +--- org.springframework.boot:spring-boot-starter:3.2.0
# |    |    +--- org.springframework.boot:spring-boot:3.2.0
# |    |    |    +--- org.springframework:spring-core:6.1.1
# |    |    |    \--- org.springframework:spring-context:6.1.1
# |    |    \--- ...

排除传递依赖

kotlin
dependencies {
    implementation("org.springframework.boot:spring-boot-starter-web:3.2.0") {
        // 排除 spring-boot-starter-tomcat,使用 Jetty
        exclude(group = "org.springframework.boot", module = "spring-boot-starter-tomcat")
    }
    
    // 排除所有传递依赖中的某个库(全局排除)
    configurations.all {
        exclude(group = "commons-logging", module = "commons-logging")
    }
}

强制指定版本

kotlin
dependencies {
    // 强制使用特定版本(即使传递依赖要求不同版本)
    implementation("com.fasterxml.jackson.core:jackson-databind") {
        version { strictly("2.15.3") }
    }
}

// 或者使用 configurations
configurations.all {
    resolutionStrategy {
        force("com.fasterxml.jackson.core:jackson-databind:2.15.3")
    }
}

本地文件依赖

kotlin
dependencies {
    // 单个 JAR 文件
    implementation(files("libs/custom-lib.jar"))
    
    // 目录下所有 JAR
    implementation(fileTree("libs") { include("*.jar") })
}

项目间依赖(多项目)

kotlin
dependencies {
    implementation(project(":core"))
    testImplementation(project(":test-support"))
}

下一步