首页 > 解决方案 > 如何将 gradle ant java 任务转换为 kotlin

问题描述

我有一个启动 H2 数据库的 gradle ant 任务。构建脚本如下所示:

apply plugin: 'java'

repositories {
    mavenCentral()
}

dependencies {
    runtime 'com.h2database:h2:1.3.168'
}

task startH2Db {
    group = 'database'
    description='Starts the H2 TCP database server on port 9092 and web admin on port 8082'
    doLast{
        ant.java( fork:true, spawn:true, classname:'org.h2.tools.Server', dir:projectDir){
            arg(value: "-tcp")
            arg(value: "-web")
            arg(value: "-tcpPort")
            arg(value: "9092")
            arg(value: "-webPort")
            arg(value: "8082")
            arg(value: "-webAllowOthers")
            classpath {
                pathelement(path:"${sourceSets.main.runtimeClasspath.asPath}")
            }
        }
    }
}

鉴于 Gradle 现在支持 Kotlin,我决定尝试将其转换build.gradlebuild.gradle.kts文件。

我正在努力寻找有关如何在 Kotlin 中执行此操作的文档。我找到了其他 ant 任务的示例,但没有像上面这样的 args。我已经做到了:

plugins {
    java
}

repositories {
    mavenCentral()
}

dependencies {
    runtime ("com.h2database:h2:1.3.168")
}

tasks {
    register("startH2Database") {
        group = "database"
        description = "Starts the H2 TCP database server on port 9092 and web admin on port 8082"
        doLast {
            ant.withGroovyBuilder {
            "java"("fork" to true, "spawn" to true, "classname" to "org.h2.tools.Server", "dir" to projectDir)
            }
        }
    }
}

如何配置参数和类路径?除了此处列出的内容之外,是否还有其他文档:https ://docs.gradle.org/current/userguide/ant.html ?

标签: javagradlekotlinant

解决方案


您可以在 Gradle Kotlin DSL 存储库中查看更多示例,例如 https://github.com/gradle/kotlin-dsl/blob/master/samples/ant/build.gradle.kts

所以你的 Ant 调用可能看起来像

ant.withGroovyBuilder {
  "java"( 
     "fork" to true, 
     "spawn" to true, 
     "classname" to "org.h2.tools.Server", 
     "dir" to projectDir
   ){
      "arg"("value" to "-tcp")
      "arg"("value" to "-web")
      "arg"("value" to "-tcpPort")
      "arg"("value" to "9092")
      "arg"("value" to "-webPort")
      "arg"("value" to "8082")
      "arg"("value" to "-webAllowOthers")
      "classpath" {
        "pathelement"(
                "path" to configurations["runtime"].asPath
            )
      }
   }
}

推荐阅读