Skip to content

项目间依赖

在多项目构建中,子项目之间可以相互依赖。

基本依赖声明

kotlin
// web/build.gradle.kts
dependencies {
    // 依赖 core 子项目(运行时包含 core 的输出)
    implementation(project(":core"))
    
    // 依赖 service:auth 子项目
    implementation(project(":service:auth"))
    
    // 仅测试时依赖
    testImplementation(project(":test-support"))
}

依赖特定配置

kotlin
// 依赖 core 子项目的测试输出(获取 core 的测试工具类)
testImplementation(project(":core") {
    targetConfiguration = "testOutput"
})

// 或者使用能力(capability)
testImplementation(project(":core").apply {
    capabilities {
        requireCapability("com.example:core-test-fixtures")
    }
})

Test Fixtures(测试夹具)

Gradle 支持创建专门的测试夹具供其他子项目使用:

kotlin
// core/build.gradle.kts
plugins {
    `java-test-fixtures`
}
kotlin
// core/src/testFixtures/java/com/example/TestHelper.java
// 放在这里的类会被打包为 test-fixtures 构件
kotlin
// web/build.gradle.kts
dependencies {
    // 使用 core 的测试夹具
    testImplementation(testFixtures(project(":core")))
}

类型安全的项目引用

kotlin
// settings.gradle.kts 中启用
enableFeaturePreview("TYPESAFE_PROJECT_ACCESSORS")

// 使用
dependencies {
    implementation(projects.core)
    implementation(projects.service.auth)
    testImplementation(projects.testSupport)
}

依赖顺序与并行

Gradle 会根据项目间依赖关系自动确定构建顺序:

bash
# 并行构建(无依赖关系的子项目并行执行)
./gradlew build --parallel

# 查看构建顺序
./gradlew build --dry-run

循环依赖

Gradle 不允许循环依赖(A 依赖 B,B 又依赖 A):

bash
# 错误信息
FAILURE: Build failed with an exception.
* What went wrong:
Circular dependency between the following tasks:
:core:compileJava
\--- :web:compileJava
     \--- :core:compileJava (*)

解决方式:提取公共部分到第三个模块 common,两个模块都依赖它。

下一步