Skip to content

Kotlin DSL 基础

Kotlin DSL 是 Gradle 8+ 的默认选择,提供完整的 IDE 支持、类型安全和自动补全。

build.gradle.kts 基本结构

kotlin
// build.gradle.kts

// 1. 插件声明
plugins {
    java
    id("org.springframework.boot") version "3.2.0"
    id("io.spring.dependency-management") version "1.1.4"
}

// 2. 项目信息
group = "com.example"
version = "1.0.0"
description = "示例项目"

// 3. Java 配置
java {
    sourceCompatibility = JavaVersion.VERSION_17
    targetCompatibility = JavaVersion.VERSION_17
}

// 4. 仓库配置
repositories {
    mavenCentral()
}

// 5. 依赖
dependencies {
    implementation("org.springframework.boot:spring-boot-starter-web")
    implementation("org.springframework.boot:spring-boot-starter-data-jpa")
    runtimeOnly("com.mysql:mysql-connector-j")
    testImplementation("org.springframework.boot:spring-boot-starter-test")
    compileOnly("org.projectlombok:lombok")
    annotationProcessor("org.projectlombok:lombok")
}

// 6. 任务配置
tasks.named<Test>("test") {
    useJUnitPlatform()
}

// 7. 自定义任务
tasks.register("printInfo") {
    group = "custom"
    description = "打印项目信息"
    doLast {
        println("项目名称: ${project.name}")
        println("项目版本: ${project.version}")
    }
}

Kotlin DSL 核心语法

变量与类型

kotlin
// val(不可变)和 var(可变)
val appVersion = "1.0.0"         // 类型推断为 String
val javaVersion: Int = 17        // 显式类型声明
var counter = 0

// 字符串模板
val greeting = "Hello, ${project.name}!"

// 多行字符串
val sql = """
    SELECT *
    FROM users
    WHERE active = true
""".trimIndent()

Lambda 表达式(替代 Groovy 闭包)

kotlin
// Kotlin lambda
tasks.register("myTask") {
    // this 是 Task 对象
    group = "custom"
    doLast {
        // this 是 Task 对象
        println("Running task: ${name}")
    }
}

属性访问

kotlin
// Kotlin DSL 中所有配置都是类型安全的
tasks.named<Jar>("jar") {
    archiveBaseName.set("my-app")      // 设置属性
    val baseName = archiveBaseName.get() // 获取属性值
}

常用配置写法

插件声明

kotlin
plugins {
    // Gradle 核心插件(直接使用名称)
    java
    `java-library`
    application
    `maven-publish`
    
    // Kotlin 插件
    kotlin("jvm") version "1.9.22"
    kotlin("plugin.spring") version "1.9.22"
    
    // 第三方插件
    id("org.springframework.boot") version "3.2.0"
    id("com.github.johnrengelman.shadow") version "8.1.1"
}

依赖声明

kotlin
dependencies {
    // 编译和运行时依赖(最常用)
    implementation("com.google.guava:guava:32.0.1-jre")
    
    // API 依赖(传递给消费者,用于库项目)
    api("org.slf4j:slf4j-api:2.0.9")
    
    // 仅编译时(如 Lombok、注解处理器)
    compileOnly("org.projectlombok:lombok:1.18.30")
    annotationProcessor("org.projectlombok:lombok:1.18.30")
    
    // 仅运行时(如数据库驱动)
    runtimeOnly("com.mysql:mysql-connector-j:8.2.0")
    
    // 测试依赖
    testImplementation("org.springframework.boot:spring-boot-starter-test")
    testImplementation("org.junit.jupiter:junit-jupiter:5.10.1")
    testRuntimeOnly("org.junit.platform:junit-platform-launcher")
    
    // 导入 BOM(管理版本)
    implementation(platform("org.springframework.boot:spring-boot-dependencies:3.2.0"))
    
    // 项目依赖(多项目构建)
    implementation(project(":core"))
}

任务配置

kotlin
// 配置已有任务
tasks.named<JavaCompile>("compileJava") {
    options.encoding = "UTF-8"
    options.compilerArgs.add("-parameters")
}

tasks.named<Test>("test") {
    useJUnitPlatform()
    maxHeapSize = "1g"
    
    // 测试过滤
    filter {
        excludeTestsMatching("*IntegrationTest")
    }
    
    // 系统属性
    systemProperty("spring.profiles.active", "test")
}

tasks.named<Jar>("jar") {
    manifest {
        attributes(
            "Main-Class" to "com.example.Application",
            "Implementation-Version" to project.version
        )
    }
}

// 配置所有 Test 类型的任务
tasks.withType<Test> {
    useJUnitPlatform()
}

// 配置所有 JavaCompile 类型的任务
tasks.withType<JavaCompile> {
    options.encoding = "UTF-8"
}

多项目配置

kotlin
// 根项目 build.gradle.kts

allprojects {
    group = "com.example"
    version = "1.0.0"
    
    repositories {
        mavenCentral()
    }
}

subprojects {
    apply(plugin = "java")
    
    dependencies {
        "testImplementation"("org.junit.jupiter:junit-jupiter:5.10.1")
    }
    
    tasks.withType<Test> {
        useJUnitPlatform()
    }
}

// 针对特定子项目
project(":web") {
    dependencies {
        "implementation"("org.springframework.boot:spring-boot-starter-web:3.2.0")
    }
}

extra 扩展属性

kotlin
// 定义扩展属性
val springBootVersion by extra("3.2.0")
val junitVersion: String by extra { "5.10.1" }

// 在其他脚本中访问
val springBootVersion: String by rootProject.extra

// 使用 extra["key"] 方式
extra["myKey"] = "myValue"
val myValue = extra["myKey"] as String

Provider API(懒加载)

Kotlin DSL 推荐使用 Provider API 进行懒加载配置:

kotlin
tasks.register<Copy>("copyDocs") {
    // 懒加载:只在任务执行时才计算值
    from(layout.projectDirectory.dir("docs"))
    into(layout.buildDirectory.dir("docs"))
}

// 使用 providers 读取属性
val buildVersion = providers.gradleProperty("buildVersion")
    .orElse("0.0.1-SNAPSHOT")

tasks.register("printVersion") {
    doLast {
        println("Version: ${buildVersion.get()}")
    }
}

Kotlin DSL 与 IDE 集成

IntelliJ IDEA 对 Kotlin DSL 提供完整支持:

  1. 自动补全:输入 tasks. 后弹出所有可用方法
  2. 类型检查:错误的属性赋值立即报错
  3. 跳转定义Ctrl+点击 跳转到 Gradle API 源码
  4. 重构支持:变量重命名会自动更新所有引用

提示:如果 IDE 自动补全失效,尝试:

  • FileSync Project with Gradle Files
  • 或点击右侧 Gradle 面板的刷新按钮

下一步