有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我正在使用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

问题

  • 如何从根build.gradle.kts设置公共依赖项

共 (1) 个答案

  1. # 1 楼答案

    我建议你读一下Gradle Kotlin DSL Primer。“理解类型安全模型访问器何时可用”一节解释了为什么不应该在此处定义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()
                }
            }
        }