如何在 Gradle Kotlin DSL 中使用 gradle.properties 的插件版本?

How to use plugin version from gradle.properties in Gradle Kotlin DSL?

现在我是这样使用的:

plugins {
    val kotlinVersion: String by project
    val springBootPluginVersion: String by project
    val springDependencyManagementPluginVersion: String by project

    id("org.jetbrains.kotlin.plugin.allopen") version kotlinVersion
    id("org.jetbrains.kotlin.jvm") version kotlinVersion
    id("org.springframework.boot") version springBootPluginVersion
    id("io.spring.dependency-management") version springDependencyManagementPluginVersion
}

这个变体可以编译并工作,但我不知道这种方式是否正确以及为什么 IntelliJ IDEA 在放置版本定义的行上显示错误:

'val Build_gradle.project: Project' can't be called in this context by implicit receiver. Use the explicit one if necessary

有几个问题对此有一些详细说明:

在最新版本的 Gradle 中执行此操作的方法是使用 settings.gradlesettings.gradle.ktspluginManagement {} 块。

在你的情况下,它可能看起来像:

pluginManagement {
  resolutionStrategy {
    eachPlugin {
      when (requested.id.id) {
        "org.jetbrains.kotlin.plugin.allopen" -> {
          val kotlinVersion: String by settings
          useVersion(kotlinVersion)
        }
        "org.jetbrains.kotlin.jvm" -> {
          val kotlinVersion: String by settings
          useVersion(kotlinVersion)
        }
        "org.springframework.boot" -> {
          val springBootPluginVersion: String by settings
          useVersion(springBootPluginVersion)
        }
        "io.spring.dependency-management" -> {
          val springDependencyManagementPluginVersion: String by settings
          useVersion(springDependencyManagementPluginVersion)
        }
      }
    }
  }
}

(Cross-post: source)

显然这在最近成为可能,如果过去不可能的话。 (几乎)来自 docs:

gradle.properties:

helloPluginVersion=1.0.0

settings.gradle.kts:

pluginManagement {
  val helloPluginVersion: String by settings
  plugins {
    id("com.example.hello") version helloPluginVersion
  }
}

现在文档说 build.gradle.kts 应该是空的,但我的测试表明你在 build.gradle.kts 中仍然需要这个:

plugins {
  id("com.example.hello")
}

版本现在由 settings.gradle.kts 确定,因此由 gradle.properties 确定,这就是我们想要的...