在gradle中添加依赖项

在gradle中添加依赖项,gradle,gradlew,Gradle,Gradlew,我不知道为什么我的依赖关系不起作用。 这是我的配置: ext { junitVersion = "4.11" libs = [ junit : dependencies.create("junit:junit:4.11") ] } configure(subprojects) { subproject -> dependencies { testCompile(libs.junit) } } 我有一个错误: *

我不知道为什么我的依赖关系不起作用。 这是我的配置:

ext {
   junitVersion = "4.11"

   libs = [
           junit : dependencies.create("junit:junit:4.11")
   ]
}

configure(subprojects) { subproject ->
    dependencies {
        testCompile(libs.junit)
    }
}
我有一个错误:

* What went wrong:
A problem occurred evaluating root project 'unit590'.
> Could not find method testCompile() for arguments [DefaultExternalModuleDependency{group='junit', name='junit', version='4.11', configuration='default'}] on org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler_Decorated@785c1069.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
谢谢你的帮助

试试这个

ext {
   junitVersion = "4.11"

   libs = [
           junit : "junit:junit:${junitVersion}"
   ]
}

configure(subprojects) { subproject ->
    dependencies {
        testCompile libs.junit
    }
}
dependencies
DSL依赖于Groovy的impl,在我手头的gradle版本中,它是这样的

public Object methodMissing(String name, Object args) {
    Configuration configuration = configurationContainer.findByName(name)
    if (configuration == null) {
        if (!getMetaClass().respondsTo(this, name, args.size())) {
            throw new MissingMethodException(name, this.getClass(), args);
        }
    }

    Object[] normalizedArgs = GUtil.collectionize(args)
    if (normalizedArgs.length == 2 && normalizedArgs[1] instanceof Closure) {
        return doAdd(configuration, normalizedArgs[0], (Closure) normalizedArgs[1])
    } else if (normalizedArgs.length == 1) {
        return doAdd(configuration, normalizedArgs[0], (Closure) null)
    }
    normalizedArgs.each {notation ->
        doAdd(configuration, notation, null)
    }
    return null;
}
这将为
dependencies{}
中的每个语句调用,并提供一个漂亮、简单的DSL来代替添加/创建等调用

我的版本将通过testCompile作为第一个字符串arg,GAV表示法字符串作为第二个arg,因此它将像往常一样进入
doAdd
方法(字符串表示法由相关的
NotationParser
(在本例中,
org.gradle.api.internal.notations.DependencyStringNotationParser
)解析)


相反,您当前的使用使它认为您正在寻求调用名为的方法
testCompile
配置是由
java
插件声明的。因此,在向
testCompile
添加依赖项之前,您必须
将插件:“java”
应用于
子项目


PS:libs的声明可以简化,如Matt的回答所示。
configure(subprojects){…}
可以简化为
subprojects{…}

非常感谢,我是新手级用户:)