Skip to content

extra 扩展属性

extra(在 Groovy DSL 中称为 ext)允许向任意 Gradle 对象动态添加属性,常用于多项目构建中共享版本号和配置。

基础用法

kotlin
// Kotlin DSL
extra["springVersion"] = "3.2.0"
extra["isRelease"] = true

// 读取
val springVersion = extra["springVersion"] as String

委托属性(推荐)

kotlin
// 定义(自动类型推断)
val springVersion by extra("3.2.0")
val maxRetries by extra(3)
val featureEnabled by extra(false)

// 在子项目中读取
val springVersion: String by rootProject.extra

多项目版本管理实战

kotlin
// 根项目 build.gradle.kts
extra.apply {
    set("springBootVersion", "3.2.0")
    set("junitVersion", "5.10.1")
    set("guavaVersion", "32.0.1-jre")
    set("lombokVersion", "1.18.30")
}

subprojects {
    val springBootVersion: String by rootProject.extra
    val junitVersion: String by rootProject.extra
    
    dependencies {
        "testImplementation"("org.junit.jupiter:junit-jupiter:$junitVersion")
    }
}

向 Task 和其他对象添加属性

kotlin
tasks.register("myTask") {
    extra["outputFile"] = file("$buildDir/output.txt")
    
    doLast {
        val output = extra["outputFile"] as File
        output.writeText("Task output")
    }
}

下一步