在gradle中添加依赖项

时间:2014-03-27 22:00:58

标签: gradle gradlew

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

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.

感谢您的帮助

2 个答案:

答案 0 :(得分:9)

testCompile配置由java插件声明。因此,在您向testCompile添加依赖项之前,您必须apply plugin: "java"subprojects

PS:libs的声明可以简化,如马特的答案所示。 configure(subprojects) { ... }可以简化为subprojects { ... }

答案 1 :(得分:1)

试试这个

ext {
   junitVersion = "4.11"

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

configure(subprojects) { subproject ->
    dependencies {
        testCompile libs.junit
    }
}

dependencies DSL依赖于Groovy的methodMissing 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)。

您当前的使用反而让它认为您正在寻求调用名为DependencyHandler#testCompile

的方法
相关问题