如何在父项目的 Gradle kotlin dsl 中定义公共依赖项?

How to define common dependencies in Gradle kotlin dsl from the parent project?

我正在使用 Kotlin DSL 设置多模块 Gradle 构建。下面是我正在使用的顶级 build.gradle.kts 文件。

subprojects {
    repositories {
        mavenCentral()
    }

    group = "com.example"
    version = "1.0.0"

    plugins.withType<JavaPlugin> {
        extensions.configure<JavaPluginExtension> {
            sourceCompatibility = JavaVersion.VERSION_11
            targetCompatibility = JavaVersion.VERSION_11

            dependencies {
                implementation(platform("org.springframework.boot:spring-boot-dependencies:2.2.2.RELEASE"))
            }

            tasks.withType<Test> {
                useJUnitPlatform()
            }
        }
    }
}

我收到以下错误

* What went wrong:
Script compilation error:

  Line 15:                 implementation(platform("org.springframework.boot:spring-boot-dependencies:2.2.2.RELEASE"))
                           ^ Unresolved reference: implementation

1 error

问题

我建议您阅读 Gradle Kotlin DSL Primer。 "Understanding when type-safe model accessors are available" 部分解释了为什么你不应该期望 implementation 在这个地方定义(强调我的):

The set of type-safe model accessors available is calculated right before evaluating the script body, immediately after the plugins {} block. Any model elements contributed after that point do not work with type-safe model accessors. For example, this includes any configurations you might define in your own build script.

因此您不能在顶级 build.gradle 中为 implementation 使用类型安全访问器,除非您在其 plugins {} 块中应用 java 插件(不建议这样做,除非根项目本身包含源代码)。

相反,使用不安全的访问器,如 Understanding what to do when type-safe model accessors are not available 部分所示,如下所示:

plugins.withType<JavaPlugin> {
        extensions.configure<JavaPluginExtension> {
            sourceCompatibility = JavaVersion.VERSION_11
            targetCompatibility = JavaVersion.VERSION_11

            dependencies {
                "implementation"(platform("org.springframework.boot:spring-boot-dependencies:2.2.2.RELEASE"))
            }

            tasks.withType<Test> {
                useJUnitPlatform()
            }
        }
    }