在迁移到 Gradle Kotlin DSL 的 Spring Boot 项目中消除警告

Getting rid of warning in a Spring Boot project being migrated to the Gradle Kotlin DSL

我正在将某些 Gradle 项目从 Groovy 迁移到 Kotlin DSL。

我正在使用 kotlin-dsl 插件并配置 Spring 引导如下:

plugins {
    java
    id("org.springframework.boot").version(Versions.springBootVersion)
    `kotlin-dsl`
}

kotlin-dsl 插件的文档要求 指定任何特定的 Kotlin 版本,如下引用:

Avoid specifying a version for the kotlin-dsl plugin:

Each Gradle release is meant to be used with a specific version of the kotlin-dsl plugin and compatibility between arbitrary Gradle releases and kotlin-dsl plugin versions is not guaranteed. Using an unexpected version of the kotlin-dsl plugin in a build will emit a warning and can cause hard to diagnose problems.

这是我的申请 class:

@SpringBootApplication
class App {
    fun main(args: Array<String>) {
        runApplication<App>(*args)
    }
}

在以 class App 开头的行下,我在 IntelliJ 中看到一条警告,告诉我:

Classes annotated with '@Configuration' could be implicitly subclassed and must not be final 

我知道这是因为 App class 应该声明为 open。 据我所知,Kotlin 的 Gradle Spring 启动插件应该负责在幕后为我制作 @SpringBootApplication 注释 class open。所以我尝试添加以下插件:

kotlin("plugin.spring") version "1.3.72"

(其中version "1.3.72"对应Kotlin版本)

如预期的那样,异常消失了。 但是,这种方法违反了不在 Gradle 配置中硬编码 Kotlin 版本的建议准则。

配置 Spring 使用 Kotlin DSL 启动的最佳实践是什么,这样我就不必在我的构建脚本中对 Kotlin 版本进行硬编码? 也许有一种方法可以消除 IntelliJ 中的警告而无需添加 kotlin("plugin.spring") version "1.3.72" 插件? 我认为这可能是 IntelliJ 特有的问题,因为即使 kotlin("plugin.spring") 不存在,从终端使用 gradle 构建或执行项目时我也没有看到任何类似的警告。

Kotlin DSL Plugin 的 Gradle 用户指南是这样描述的:

The Kotlin DSL Plugin provides a convenient way to develop Kotlin-based projects that contribute build logic. That includes buildSrc projects, included builds and Gradle plugins.

您的 Spring 引导应用程序不提供构建逻辑,您可能不应该为此使用该插件。如果您在 Kotlin 中开发 Gradle 插件,那么它会更有意义。在这种情况下,您应该使用与您正在构建的版本提供的 Kotlin DSL 相同版本的 Gradle API,因为针对另一个版本可能有点棘手。

我会删除该插件,而不是明确说明您的配置。您将需要在构建文件中添加几行,但这样复杂类路径就不会被您不需要的 DSL 内容污染。

这也意味着您需要对 Kotlin 版本进行硬编码,但这是一件好事,否则您将依赖于您正在构建的 Gradle 版本中包含的任何内容。

例如:

plugins {
    id("org.springframework.boot") version "2.3.0.RELEASE"
    kotlin("jvm") version "1.3.72"
    kotlin("plugin.spring") version "1.3.72"
}

dependencies {
    implementation(platform("org.springframework.boot:spring-boot-dependencies:2.3.0.RELEASE"))
    implementation(platform("org.jetbrains.kotlin:kotlin-bom"))
    implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
    implementation("org.springframework.boot:spring-boot-starter")
}