Gradle - Include Properties File

前端 未结 9 1020
天命终不由人
天命终不由人 2020-12-08 04:13

How would I include a properties file in Gradle?

For example in Ant, I could do the following:



        
相关标签:
9条回答
  • 2020-12-08 04:31

    The accepted answer works unless you want to add the properties to the project, since this is the first search result I'll add my solution which works in gradle 3.x. An easy way to do it is through ant.

    ant {
        property(file: 'properties.file')
    }
    

    If you need to convert the property to Camel Case for easy access in your script (remember dot based syntax expects and actual object to exist in gradle):

    println "property value:{dot.property.from.file}" //this will fail.
    def camelCaseProperty = project.getProperties().get("dot.property.from.file")
    println "camelCaseProperty:${camelCaseProperty}"  //this wont fail
    

    If you need a default value if it's not specified:

    def propertyWithDefault = project.getProperties().get("dot.property.from.file","defaultValue");
    

    By using this method, at least with IntelliJ/Android Studio, the IDE will link your properties file and gradle script and add completion, reference checking, etc.

    0 讨论(0)
  • 2020-12-08 04:35

    You could do it using the java syntax, e.g.:

    Properties props = new Properties()
    InputStream ins = new FileInputStream("/path/file.properties")
    props.load(ins)
    ins.close()
    

    This should work in any groovy script. There might be a more "groovy" way of doing it though, using closures or some other fancy shortcut.

    EDIT: "in" is a reserved word in groovy. A variable can't be named that way, renaming it to "ins"

    0 讨论(0)
  • 2020-12-08 04:46

    What you propably are looking for is something like:

        Properties props = new Properties()
        props.load(new FileInputStream("$project.rootDir/profile/"+"$environment"+".properties"))
        props.each { prop ->
          project.ext.set(prop.key, prop.value)
        }
    

    Your properties should then be accessible directly through their name. I.e.:

      println "$jdbcURL"
      println project.jdbcURL
    

    Theres probably a reason (shadowing?) why its a bad idea to do this? Not sure why its not supported out of the box or can be found somewhere else.

    0 讨论(0)
提交回复
热议问题