设置Gradle子项目的属性

时间:2018-07-12 06:03:37

标签: gradle build build.gradle

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

def usefulMethod() {
    return 'foo'
}

ext {
    foo = 'bar'
    usefulMethod = this.&usefulMethod
}

然后使用build.gradle将其导入子项目apply from: './properties.gradle'

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

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

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

1 个答案:

答案 0 :(得分:0)

普通的ext是ENTIRE项目,根项目和所有子项目的扩展名。为了避免在每次通过apply from...包含文件时污染根名称空间,应改为使用project.extproject是指当前正在构建的项目或子项目。例如,可以使用以下文件apply fromdownloadFile函数添加到当前项目:

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
            }
        }
    }
}
相关问题