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

在Gradle Kotlin DSL中注册和创建有什么区别,gradle,kotlin,gradle-kotlin-dsl,Gradle,Kotlin,Gradle Kotlin Dsl,Gradle(5.0+)中有两种创建任务的方法: 及 基本上相同的API,那么有什么区别呢?请参见: 上面的示例依赖于配置避免API。如果您需要或想要急切地配置或注册容器元素,只需将named()替换为getByName(),将register()替换为create() 创建和注册(或5.0之前的Gradle版本中的创建和注册)之间的差异与任务配置避免新API有关,详细说明如下(请参阅): 如何延迟任务创建 此功能要求生成作者通过将任务创建从TaskContainer.create(java.l

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

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

请参见:

上面的示例依赖于配置避免API。如果您需要或想要急切地配置或注册容器元素,只需将named()替换为getByName(),将register()替换为create()

创建
注册
(或5.0之前的Gradle版本中的
创建
注册
)之间的差异与
任务配置避免
新API有关,详细说明如下(请参阅):

如何延迟任务创建

此功能要求生成作者通过将任务创建从TaskContainer.create(java.lang.String)API迁移到TaskContainer.register(java.lang.String)API来选择加入。寄存器(…​) API注册了一个任务,当且仅当需要该任务时,才会在以后创建该任务…​) API在被调用时继续急切地创建和配置任务


公认的答案很好,但我想补充一点,如果您想实际使用由
created
/
registing
调用创建的引用,那么API将有所不同。比较

create<MavenPublication>("main") {
    …

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

    artifact(sourcesJar)
}

这是因为
artifact(…)
不支持惰性配置API,请您在@eskatos does Gradle上提交一个bug,它仍然不支持
artifact(…)
?它不支持,请看它现在支持它(自2020年1月起;请看相同的问题)总之,
寄存器效率更高,将推迟创建和配置,直到需要时才进行。
。此处参考:
tasks {
    val javadocJar by registering(Jar::class) {
        val javadoc by tasks

        from(javadoc)
        classifier = "javadoc"
    }
}
tasks.named("check")                  
tasks.register("myTask1")
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())
}
* 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()