在这些日子里,我正在尝试编写一些代码来体验Spring 5中的Spring反应特性和kotlin扩展,并且我还准备了一个gradle Kotlin DSL build.gradle.kt来配置gradle构建 .
build.gradle.kt
是由http://start.spring.io生成的Spring Boot模板代码转换而来的 .
但是Gradle无法检测到 buildscript
中的 ext
.
buildscript {
ext { }
}
ext
将导致Gradle构建错误 .
为了使 classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion")
和 compile("org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlinVersion")
中的变量起作用,我以艰难的方式添加了变量 .
val kotlinVersion = "1.1.4"
val springBootVersion = "2.0.0.M3"
但我必须在全球顶级位置声明它们并在 buildscript
中复制它们 .
代码:https://github.com/hantsy/spring-reactive-sample/blob/master/kotlin-gradle/build.gradle.kts
是否有优雅的方法使 ext
工作?
Update :有一些丑陋的方法:
- 来自Gradle Kotlin DSL示例https://github.com/gradle/kotlin-dsl/tree/master/samples/project-properties,声明了gradel.properties中的属性 .
kotlinVersion = 1.1.4
springBootVersion = 2.0.0.M3
并在build.gradle.kts中使用它 .
buildScript{
val kotlinVersion by project
}
val kotlinVersion by project //another declare out of buildscript block.
- 与上面类似,在buildScript块中声明它们:
buildScript{
extra["kotlinVersion"] = "1.1.4"
extra["springBootVersion"] = "2.0.0.M3"
val kotlinVersion: String by extra
}
val kotlinVersion: String by extra//another declare out of buildscript block.
我怎样才能避免重复 val kotlinVersion: String by extra ?
3 回答
对我有用的是在
allprojects
中使用ext
而不是buildscript
,所以在你的顶层build.gradle.kts
那么你可以在像这样的模块中的
build.gradle.kts
文件中使用它:使用Kotlin DSL ext已经改为额外的,它可以在buildscript下使用 .
例如: -
kotlin-gradle-dsl中的全局属性:
https://stackoverflow.com/a/53594357/3557894
Kotlin版本嵌入到kotlin-gradle-dsl中 .
您可以使用嵌入版本的dependecies,如下所示: