gradle.properties
gradlePropertiesProp=gradlePropertiesValue
systemProjectProp=shouldBeOverWrittenBySystemProp
envProjectProp=shouldBeOverWrittenByEnvProp
systemProp.system=systemValue
build.gradle
task printProps << {
println commandLineProjectProp
println gradlePropertiesProp
println systemProjectProp
println envProjectProp
println System.properties['system']
}
gradle -q -PcommandLineProjectProp=commandLineProjectPropValue -Dorg.gradle.project.systemProjectProp=systemPropertyValue printProps
的输出结果
> gradle -q -PcommandLineProjectProp=commandLineProjectPropValue -Dorg.gradle.project.systemProjectProp=systemPropertyValue printProps
commandLineProjectPropValue
gradlePropertiesValue
systemPropertyValue
envPropertyValue
systemValue
检查项目的属性
当你要使用一个变量时,你可以仅通过其名称在构建脚本中访问一个项目的属性。如果此属性不存在,则会引发异常,并且构建失败。如果您的构建脚本依赖于一些可选属性,而这些属性用户可能在比如 gradle.properties 文件中设置,您就需要在访问它们之前先检查它们是否存在。你可以通过使用方法 hasProperty('propertyName') 来进行检查,它返回 true 或 false。
使用外部构建脚本配置项目
您可以使用外部构建脚本来配置当前项目。Gradle 构建语言的所有内容在外部脚本中也可以使用。您甚至可以在外部脚本中应用其他脚本。
使用外部构建脚本配置项目
build.gradle
apply from: 'other.gradle'
other.gradle
println "configuring $project"
task hello << {
println 'hello from other script'
}
gradle -q hello的输出结果
> gradle -q hello
configuring root project 'configureProjectUsingScript'
hello from other script
配置任意对象
您可以用以下非常易理解的方式配置任意对象。
配置任意对象
build.gradle
task configure << {
pos = configure(new java.text.FieldPosition(10)) {
beginIndex = 1
endIndex = 5
}
println pos.beginIndex
println pos.endIndex
}
gradle -q configure 的输出结果
> gradle -q configure
1
5
使用外部脚本配置任意对象
你还可以使用外部脚本配置任意对象
使用脚本配置任意对象
build.gradle
task configure << {
pos = new java.text.FieldPosition(10)
// Apply the script
apply from: 'other.gradle', to: pos
println pos.beginIndex
println pos.endIndex
}
other.gradle
beginIndex = 1;
endIndex = 5;
gradle -q configure 的输出结果
> gradle -q configure
1
5
缓存
为了提高响应速度,默认情况下 Gradle 会缓存所有已编译的脚本。这包括所有构建脚本,初始化脚本和其他脚本。你第一次运行一个项目构建时, Gradle 会创建 .gradle 目录,用于存放已编译的脚本。下次你运行此构建时, 如果该脚本自它编译后没有被修改,Gradle 会使用这个已编译的脚本。否则该脚本会重新编译,并把最新版本存在缓存中。如果您通过 --recompile-scripts 选项运行 Gradle ,会丢弃缓存的脚本,然后重新编译此脚本并将其存在缓存中。通过这种方式,您可以强制 Gradle 重新生成缓存。
标签:Gradle
相关阅读 >>
更多相关阅读请进入《Gradle》频道 >>