在Gradle之前我和Maven合作,Maven有像dependencyManagement和pluginManagement这样的东西,允许在“属性”的帮助下将所有版本“DRY”保存在一个地方。
Gradle支持项目属性,因此我可以声明如下版本:
buildscript {
ext.kotlin_version = '1.1.61'
repositories {
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
但这种方法不适用于plugins {} DSL。我不能写这样的东西:
plugins {
id 'org.jetbrains.kotlin:kotlin-gradle-plugin' version $kotlin_version
}
根据文件:
值必须是文字的(例如常量字符串,而不是变量)
有没有办法解决这个限制?
我认为你可以将ext
闭包放在一个单独的properties.gradle
中,然后在buildscript
和project
构建中引用两次属性(buildscript
块在开始时,在groovy脚本的任何其他部分之前进行评估)。
例如,在$projectRoot/gradle/properties.gradle
中如下:
ext {
kotlinVersion = '1.1.61' // NOTE, the naming convention is better with kotlinVersion instead of kotlin_version
}
而你的$projectRoot/build.gradle
看起来像这样:
buildscript {
apply from: "gradle/properties.gradle"
repositories {
jcenter()
}
dependencies {
println "In buildscript, kotlinVersion is $kotlinVersion"
}
}
apply plugin: 'java'
apply from: "gradle/properties.gradle"
repositories {
jcenter()
}
dependencies {
println "In project, kotlinVersion is $kotlinVersion"
}
当你运行./gradlew dependencies
时,它会显示填充的版本:
> Configure project :
In buildscript, kotlinVersion is 1.1.61
In project, kotlinVersion is 1.1.61