在Gradle Kotlin DSL中注册和创建之间有什么区别

时间:2018-12-06 15:01:02

标签: gradle kotlin gradle-kotlin-dsl

在Gradle(5.0+)中有两种创建方法,即任务:

tasks {
    val javadocJar by creating(Jar::class) {
        val javadoc by tasks

        from(javadoc)
        classifier = "javadoc"
    }
}

tasks {
    val javadocJar by registering(Jar::class) {
        val javadoc by tasks

        from(javadoc)
        classifier = "javadoc"
    }
}

基本上相同的API,有什么区别?

2 个答案:

答案 0 :(得分:5)

请参见https://docs.gradle.org/current/userguide/kotlin_dsl.html#using_the_container_api

tasks.named("check")                  
tasks.register("myTask1")
  

以上示例依赖于配置避免API。如果您需要或希望配置或注册容器元素,只需将named()替换为getByName()并将register()替换为create()。

creatingregistering之间的差异(或在5.0之前的Gradle版本中,createregister之间的差异与Task Configuration Avoidance新API相关, here(请参见this section)中的详细信息:

  

如何推迟任务创建?

     

此功能要求构建作者选择加入,方法是将任务创建从TaskContainer.create(java.lang.String)API迁移到TaskContainer.register(java.lang.String)API。 register(…)API仅在需要时才注册要在以后创建的任务。当调用create(…)API时,它会继续急切地创建和配置任务。

答案 1 :(得分:2)

可接受的答案很好,但是我想补充一点,如果您想稍后使用由created / registering调用创建的引用,那么API会有区别。比较

create<MavenPublication>("main") {
    …

    val sourcesJar by tasks.creating(Jar::class) {
        val sourceSets: SourceSetContainer by project
        from(sourceSets["main"].allJava)
        classifier = "sources"
    }

    artifact(sourcesJar)
}

create<MavenPublication>("main") {
    …

    val sourcesJar by tasks.registering(Jar::class) {
        val sourceSets: SourceSetContainer by project
        from(sourceSets["main"].allJava)
        classifier = "sources"
    }

    artifact(sourcesJar.get())
}

在注册的情况下,由于它是懒惰的,因此您将需要额外的.get()调用,否则将获得异常:

* What went wrong:
Cannot convert the provided notation to an object of type MavenArtifact: task ':experiments:sourcesJar'.
The following types/formats are supported:
  - Instances of MavenArtifact.
  - Instances of AbstractArchiveTask, for example jar.
  - Instances of PublishArtifact
  - Maps containing a 'source' entry, for example [source: '/path/to/file', extension: 'zip'].
  - Anything that can be converted to a file, as per Project.file()