设置Gradle子项目的属性

设置Gradle子项目的属性,gradle,build,build.gradle,Gradle,Build,Build.gradle,我有一个多项目的渐变构建。在每个子项目中,我都有一个properties.gradle文件,如下所示: def usefulMethod() { return 'foo' } ext { foo = 'bar' usefulMethod = this.&usefulMethod } 然后我使用apply from:'./properties.gradle'将其导入子项目build.gradle 但是,如果两个子项目导入具有相同名称的变量,则会出现以下错误: C

我有一个多项目的渐变构建。在每个子项目中,我都有一个
properties.gradle
文件,如下所示:

def usefulMethod() {
    return 'foo'
}

ext {
    foo = 'bar'
    usefulMethod = this.&usefulMethod
}
然后我使用
apply from:'./properties.gradle'
将其导入子项目
build.gradle

但是,如果两个子项目导入具有相同名称的变量,则会出现以下错误:

Cannot add extension with name 'foo', as there is an extension already registered with that name.

似乎添加到
ext
会影响整个项目,而不仅仅是我想要的子项目。从子项目中的外部文件导入属性和变量而不泄漏到整个项目构建中的正确方法是什么

普通
ext
是整个项目、根项目和所有子项目的扩展。为了避免在通过
apply from…
包含文件时污染根命名空间,应改用
project.ext
<代码>项目指当前正在构建的项目或子项目。例如,以下文件可以是
apply from
'd,以将
下载文件
功能添加到当前项目中:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'de.undercouch:gradle-download-task:3.4.3'
    }
}

project.ext {
    apply plugin: de.undercouch.gradle.tasks.download.DownloadTaskPlugin

    downloadFile = { String url, File destination ->
        if (destination.exists()) {
            println "Skipping download because ${destination} already exists"
        } else {
            download {
                src url
                dest destination
            }
        }
    }
}