在不同文件中配置Gradle依赖项

时间:2019-01-29 20:40:04

标签: android gradle android-gradle

我正在使用放置在build.gradle(Project)所在目录中的外部dependencies.gradle文件。我正在使用以下命令

build.gradle(项目)

apply from: 'dependencies.gradle'

dependencies.gradle

ext {
SUPPORT_LIB_VERSION = '28.0.0'
dependencies = [
        ANNOTATIONS: "com.android.support:support-annotations:$SUPPORT_LIB_VERSION"
]}

build.gradle(应用程序)

api rootProject.ext.dependencies.ANNOTATIONS

上面的代码工作得很好。我想知道如何使用相同的方法排除组或模块? 让我写下我被困住的地方

dependencies = [
        espresso: ("com.android.support.test.espresso:espresso-contrib:3.0.2") {
            exclude group: 'com.android.support', module: 'appcompat'
            exclude group: 'com.android.support', module: 'support-v4'
            exclude group: 'com.android.support', module: 'recyclerview-v7'
        }
]

我收到此错误

No signature of method: java.lang.String.call() is applicable for argument types: (dependencies_83n19kvhft5hx8evun34kydx1$_run_closure1$_closure2) values: [dependencies_83n19kvhft5hx8evun34kydx1$_run_closure1$_closure2@759d33fd] Possible solutions: wait(), any(), wait(long), take(int), any(groovy.lang.Closure), each(groovy.lang.Closure)

2 个答案:

答案 0 :(得分:0)

如果要排除某些数据,则需要在build.gradle文件中进行处理:

dependencies.gradle

dependencies = [
    espresso: "com.android.support.test.espresso:espresso-contrib:3.0.2"
]

build.gradle

testImplementation(rootProject.ext.dependencies.espresso) {
    exclude group: 'com.android.support', module: 'appcompat'
    exclude group: 'com.android.support', module: 'support-v4'
    exclude group: 'com.android.support', module: 'recyclerview-v7'
}

因为implementation(object) { //Closure... }是一种具有2个参数的方法:对象和操作。您可以看到this doc.

答案 1 :(得分:0)

您的“依赖项”是字符串数组,而不是依赖项。在对字符串类型添加闭包(groovy lambda)时抛出了异常

此:

   {
        exclude group: 'com.android.support', module: 'appcompat'
        exclude group: 'com.android.support', module: 'support-v4'
        exclude group: 'com.android.support', module: 'recyclerview-v7'
    }

仅用于依赖项。您可以仅从依赖项{}阻止中添加排除

尝试创建 espresso.gragle

apply from: "$rootDir/dependencies.gradle"

dependencies {
    androidTestImplementation(
        rootProject.ext.dependencies.ESPRESSO {
            exclude group: 'com.android.support', module: 'appcompat'
            exclude group: 'com.android.support', module: 'support-v4'
            exclude group: 'com.android.support', module: 'recyclerview-v7'
        }
    )
}

接下来将其添加到您的 build.gradle(应用程序)

apply from: "$rootDir/espresso.gradle"

我还建议像这样向模块添加依赖项:

dependencies.gradle

ext.libs = [:]

def versions = [:]
versions.support = "28.0.0"

def libs = [:]

def support = [:]
support.annotations = "com.android.support:support-v4:$versions.support"
support.another = "com.android.support:another:$versions.support"
// another support dependencies
libs.support = support

ext.libs = libs

build.gradle(应用程序)

apply from: "$rootDir/dependencies.gradle" // path to dependencies.gradle

dependencies(
    api(
        libs.support.annotations,
        libs.support.another
    )
)