【问题标题】:setting properties for Gradle subproject为 Gradle 子项目设置属性
【发布时间】:2018-07-12 06:03:37
【问题描述】:

我有一个多项目 Gradle 构建。在每个子项目中,我都有一个 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 会影响整个项目,而不仅仅是我想要的子项目。从子项目中的外部文件导入属性和变量而不将它们泄漏到整个项目构建中的正确方法是什么?

【问题讨论】:

    标签: gradle build build.gradle


    【解决方案1】:

    普通的ext 是整个项目、根项目和所有子项目的扩展。为了避免在通过apply from... 包含文件时污染根命名空间,您应该改用project.extproject 指的是当前正在构建的项目或子项目。例如,下面的文件可以是 apply from'd 以向当前项目添加 downloadFile 函数:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-20
      • 2012-08-26
      • 2012-02-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多