Skip to content

依赖配置(Configuration)

Configuration 是 Gradle 依赖管理的核心概念,代表一组依赖的集合以及解析规则。

标准配置(Java 插件提供)

implementation       → 编译+运行时,不暴露给消费者
api                  → 编译+运行时,暴露给消费者(java-library 插件)
compileOnly          → 仅编译时
runtimeOnly          → 仅运行时
testImplementation   → 测试编译+运行时
testCompileOnly      → 仅测试编译时
testRuntimeOnly      → 仅测试运行时
annotationProcessor  → 注解处理器

implementation vs api

这是 Java 库项目中最重要的区别:

kotlin
// 使用 java-library 插件
plugins {
    `java-library`
}

dependencies {
    // api:会暴露给依赖本库的项目(传递性依赖)
    // 例如:如果你的库的公共 API 中使用了 Guava 类型
    api("com.google.guava:guava:32.0.1-jre")
    
    // implementation:内部使用,不暴露给消费者(推荐默认选择)
    // 例如:内部日志库,消费者不需要知道
    implementation("org.slf4j:slf4j-api:2.0.9")
}

消费者项目

kotlin
dependencies {
    implementation(project(":my-library"))
    // 可以直接使用 Guava(api 传递过来)
    // 不能直接使用 slf4j(implementation 不传递)
}

自定义 Configuration

kotlin
// 创建自定义配置
val integrationTest by configurations.creating {
    isCanBeResolved = true
    isCanBeConsumed = false
    extendsFrom(configurations.testImplementation.get())
}

// 添加依赖
dependencies {
    integrationTest("com.example:integration-test-support:1.0")
}

// 在任务中使用
tasks.register<Test>("integrationTest") {
    classpath = integrationTest + sourceSets["integrationTest"].output
    testClassesDirs = sourceSets["integrationTest"].output.classesDirs
}

配置继承

kotlin
// testImplementation 默认继承自 implementation
// 所以 implementation 中的依赖,在测试中也可用

configurations {
    testImplementation {
        extendsFrom(implementation.get())
    }
}

解析配置

kotlin
// 获取配置的所有文件(用于自定义任务)
tasks.register("listDeps") {
    doLast {
        configurations["compileClasspath"].resolvedConfiguration.resolvedArtifacts.forEach {
            println("${it.moduleVersion.id}: ${it.file}")
        }
    }
}

下一步