问题描述
如何在build.gradle文件中设置属性并允许每个开发人员在本地覆盖它?我试过:
gradle.properties:
MY_NAME =Jonathon
MY_COLOR =blue
build.gradle:
ext.MY_NAME =John Doe
任务showit<< {
printlnMY_NAME [+ MY_NAME +] ;
printlnMY_COLOR [+ MY_COLOR +];
}
gradle showit
给出:
:showit
MY_NAME [John Doe]
MY_COLOR [blue]
我认为在项目根目录下的gradle.properties文件中定义的属性会覆盖具有相同名称的属性在build.gradle中,但这似乎并非如此。它只填补了一个缺失的属性。
检查项目是否有属性,如果没有,则将其设置为默认值:
如果(!project.hasProperty('MY_NAME')){b
$ b
ext {
MY_NAME ='John Doe'
}
}
请参阅:
如果您需要为多个属性执行此操作,您可以定义一个函数:
def setPropertyDefaultValueIfNotCustomized(propertyName,defaultValue){
if(!project.hasProperty(propertyName)){
ext [propertyName] = defaultValue
}
}
分机{
setPropertyDefaultValueIfNotCustomized('MY_NAME','John Doe )
}
How can I set a property in the build.gradle file and allow each developer to override it locally? I tried:
gradle.properties:
MY_NAME = "Jonathon"
MY_COLOR = "blue"
build.gradle:
ext.MY_NAME = "John Doe"
task showit <<{
println "MY_NAME[" + MY_NAME + "]";
println "MY_COLOR[" + MY_COLOR + "]";
}
gradle showit
gives:
:showit
MY_NAME[John Doe]
MY_COLOR["blue"]
I thought that a property defined in a gradle.properties file at the project root would override a property with the same name defined in build.gradle, but this does not appear to be the case. It only fills in for a missing property.
Check whether the project has a property, and if not, set it to the default value:
ext {
if (!project.hasProperty('MY_NAME')) {
MY_NAME = 'John Doe'
}
}
See: https://docs.gradle.org/current/userguide/build_environment.html#sub:checking_for_project_properties
If you need to do this for multiple properties, you can define a function:
def setPropertyDefaultValueIfNotCustomized(propertyName, defaultValue) {
if (!project.hasProperty(propertyName)) {
ext[propertyName] = defaultValue
}
}
ext {
setPropertyDefaultValueIfNotCustomized('MY_NAME', 'John Doe')
}
这篇关于我如何覆盖build.gradle中定义的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!