How can I override a property defined in build.gra

2019-06-21 19:39发布

问题:

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.

回答1:

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')
}


回答2:

i think you can define a local variable and then override it like this

  def dest = "name"

  task copy(type: Copy) {
     from "source"
     into name
  }

see this doc



标签: gradle