Skip to content

Groovy DSL 与 Kotlin DSL 对照表

本文提供两种 DSL 的语法对照,便于在两种 DSL 之间切换。

基本语法差异

特性Groovy DSLKotlin DSL
文件扩展名.gradle.gradle.kts
字符串单引号或双引号只能双引号
变量定义def x = ...val x = ... / var x = ...
方法调用括号可省略不可省略
字符串插值"${var}""${var}"
类型声明可选(动态类型)通常必须(静态类型)

插件声明

groovy
// Groovy DSL
plugins {
    id 'java'
    id 'org.springframework.boot' version '3.2.0'
    id 'io.spring.dependency-management' version '1.1.4'
}
kotlin
// Kotlin DSL
plugins {
    java
    id("org.springframework.boot") version "3.2.0"
    id("io.spring.dependency-management") version "1.1.4"
}

项目属性

groovy
// Groovy DSL
group = 'com.example'
version = '1.0.0'
description = '我的应用'
kotlin
// Kotlin DSL
group = "com.example"
version = "1.0.0"
description = "我的应用"

仓库配置

groovy
// Groovy DSL
repositories {
    mavenCentral()
    maven { url 'https://maven.aliyun.com/repository/public' }
    maven {
        url 'https://private.example.com/maven'
        credentials {
            username = System.getenv('MAVEN_USER')
            password = System.getenv('MAVEN_PASS')
        }
    }
}
kotlin
// Kotlin DSL
repositories {
    mavenCentral()
    maven { url = uri("https://maven.aliyun.com/repository/public") }
    maven {
        url = uri("https://private.example.com/maven")
        credentials {
            username = System.getenv("MAVEN_USER")
            password = System.getenv("MAVEN_PASS")
        }
    }
}

依赖声明

groovy
// Groovy DSL
dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web:3.2.0'
    implementation platform('org.springframework.boot:spring-boot-dependencies:3.2.0')
    compileOnly 'org.projectlombok:lombok:1.18.30'
    annotationProcessor 'org.projectlombok:lombok:1.18.30'
    testImplementation 'org.junit.jupiter:junit-jupiter:5.10.1'
    
    // 排除依赖
    implementation('com.example:lib:1.0') {
        exclude group: 'commons-logging', module: 'commons-logging'
    }
    
    // 项目依赖
    implementation project(':core')
}
kotlin
// Kotlin DSL
dependencies {
    implementation("org.springframework.boot:spring-boot-starter-web:3.2.0")
    implementation(platform("org.springframework.boot:spring-boot-dependencies:3.2.0"))
    compileOnly("org.projectlombok:lombok:1.18.30")
    annotationProcessor("org.projectlombok:lombok:1.18.30")
    testImplementation("org.junit.jupiter:junit-jupiter:5.10.1")
    
    // 排除依赖
    implementation("com.example:lib:1.0") {
        exclude(group = "commons-logging", module = "commons-logging")
    }
    
    // 项目依赖
    implementation(project(":core"))
}

Java 配置

groovy
// Groovy DSL
java {
    sourceCompatibility = JavaVersion.VERSION_17
    targetCompatibility = JavaVersion.VERSION_17
    withSourcesJar()
    withJavadocJar()
}
kotlin
// Kotlin DSL
java {
    sourceCompatibility = JavaVersion.VERSION_17
    targetCompatibility = JavaVersion.VERSION_17
    withSourcesJar()
    withJavadocJar()
}

任务定义

groovy
// Groovy DSL
task hello {
    group = 'custom'
    description = '打招呼'
    doLast {
        println 'Hello, Gradle!'
    }
}

// 带类型
task copyFiles(type: Copy) {
    from 'src/config'
    into "$buildDir/config"
}
kotlin
// Kotlin DSL
tasks.register("hello") {
    group = "custom"
    description = "打招呼"
    doLast {
        println("Hello, Gradle!")
    }
}

// 带类型
tasks.register<Copy>("copyFiles") {
    from("src/config")
    into("$buildDir/config")
}

任务配置(已有任务)

groovy
// Groovy DSL
tasks.named('test') {
    useJUnitPlatform()
    maxHeapSize = '1g'
}

// 批量配置同类型任务
tasks.withType(JavaCompile) {
    options.encoding = 'UTF-8'
}
kotlin
// Kotlin DSL
tasks.named<Test>("test") {
    useJUnitPlatform()
    maxHeapSize = "1g"
}

// 批量配置同类型任务
tasks.withType<JavaCompile> {
    options.encoding = "UTF-8"
}

扩展属性(extra/ext)

groovy
// Groovy DSL
ext {
    springVersion = '3.2.0'
    junitVersion = '5.10.1'
}

// 访问
dependencies {
    implementation "org.springframework.boot:spring-boot-starter-web:${springVersion}"
}
kotlin
// Kotlin DSL
val springVersion by extra("3.2.0")
val junitVersion by extra("5.10.1")

// 或
extra["springVersion"] = "3.2.0"

// 访问(子项目)
val springVersion: String by rootProject.extra

多项目配置

groovy
// Groovy DSL
allprojects {
    group = 'com.example'
}

subprojects {
    apply plugin: 'java'
    
    repositories {
        mavenCentral()
    }
    
    dependencies {
        testImplementation 'org.junit.jupiter:junit-jupiter:5.10.1'
    }
}

project(':web') {
    dependencies {
        implementation 'org.springframework.boot:spring-boot-starter-web:3.2.0'
    }
}
kotlin
// Kotlin DSL
allprojects {
    group = "com.example"
}

subprojects {
    apply(plugin = "java")
    
    repositories {
        mavenCentral()
    }
    
    dependencies {
        "testImplementation"("org.junit.jupiter:junit-jupiter:5.10.1")
    }
}

project(":web") {
    dependencies {
        "implementation"("org.springframework.boot:spring-boot-starter-web:3.2.0")
    }
}

发布配置

groovy
// Groovy DSL
publishing {
    publications {
        mavenJava(MavenPublication) {
            from components.java
            pom {
                name = 'My Library'
                description = 'A sample library'
            }
        }
    }
    repositories {
        maven {
            url = version.endsWith('SNAPSHOT') ?
                'https://oss.sonatype.org/content/repositories/snapshots/' :
                'https://oss.sonatype.org/service/local/staging/deploy/maven2/'
            credentials {
                username = System.getenv('OSSRH_USERNAME')
                password = System.getenv('OSSRH_PASSWORD')
            }
        }
    }
}
kotlin
// Kotlin DSL
publishing {
    publications {
        create<MavenPublication>("mavenJava") {
            from(components["java"])
            pom {
                name.set("My Library")
                description.set("A sample library")
            }
        }
    }
    repositories {
        maven {
            url = uri(
                if (version.toString().endsWith("SNAPSHOT"))
                    "https://oss.sonatype.org/content/repositories/snapshots/"
                else
                    "https://oss.sonatype.org/service/local/staging/deploy/maven2/"
            )
            credentials {
                username = System.getenv("OSSRH_USERNAME")
                password = System.getenv("OSSRH_PASSWORD")
            }
        }
    }
}

条件判断

groovy
// Groovy DSL
if (project.hasProperty('release')) {
    version = '1.0.0'
} else {
    version = '1.0.0-SNAPSHOT'
}
kotlin
// Kotlin DSL
version = if (project.hasProperty("release")) "1.0.0" else "1.0.0-SNAPSHOT"

动态任务创建

groovy
// Groovy DSL
['dev', 'test', 'prod'].each { env ->
    task "deploy${env.capitalize()}" {
        group = 'deploy'
        doLast { println "部署到 ${env}" }
    }
}
kotlin
// Kotlin DSL
listOf("dev", "test", "prod").forEach { env ->
    tasks.register("deploy${env.replaceFirstChar { it.uppercase() }}") {
        group = "deploy"
        doLast { println("部署到 $env") }
    }
}

文件操作

groovy
// Groovy DSL
task copyConfig(type: Copy) {
    from 'src/config'
    into "${buildDir}/config"
    include '*.yml'
    filter { line -> line.replace('@VERSION@', version) }
}
kotlin
// Kotlin DSL
tasks.register<Copy>("copyConfig") {
    from("src/config")
    into("${buildDir}/config")
    include("*.yml")
    filter { line -> line.replace("@VERSION@", version.toString()) }
}