Java 使用变量指定依赖项版本时生成失败

Java 使用变量指定依赖项版本时生成失败,java,gradle,Java,Gradle,我正在尝试将我的maven项目迁移到gradle。我在变量springVersion中为所有项目指定spring版本。但是由于某种原因,构建在一个特定的依赖项上失败了org.springframework:springweb:springVersion。当我直接键入版本时,org.springframework:springweb:3.1.2.RELEASE。这是我的build.gradle文件: subprojects { apply plugin: 'java' apply

我正在尝试将我的maven项目迁移到gradle。我在变量springVersion中为所有项目指定spring版本。但是由于某种原因,构建在一个特定的依赖项上失败了org.springframework:springweb:springVersion。当我直接键入版本时,org.springframework:springweb:3.1.2.RELEASE。这是我的build.gradle文件:

subprojects {
    apply plugin: 'java'
    apply plugin: 'eclipse-wtp'

    ext {    
        springVersion = "3.1.2.RELEASE"
    }
    repositories {
       mavenCentral()
    }

    dependencies {
        compile 'org.springframework:spring-context:springVersion'
        compile 'org.springframework:spring-web:springVersion'
        compile 'org.springframework:spring-core:springVersion'
        compile 'org.springframework:spring-beans:springVersion'

        testCompile 'org.springframework:spring-test:3.1.2.RELEASE'
        testCompile 'org.slf4j:slf4j-log4j12:1.6.6'
        testCompile 'junit:junit:4.10'
    }

    version = '1.0'

    jar {
        manifest.attributes provider: 'gradle'
    }
}
错误消息:

* What went wrong:
Could not resolve all dependencies for configuration ':hi-db:compile'.
> Could not find group:org.springframework, module:spring-web, version:springVersion.
  Required by:
      hedgehog-investigator-project:hi-db:1.0
执行测试时,org.springframework:spring test:3.1.2.RELEASE也是如此


是什么导致了这个问题以及如何解决这个问题?

您正在使用
springVersion
作为版本。声明依赖项的正确方法是:

// notice the double quotes and dollar sign
compile "org.springframework:spring-context:$springVersion"
这是使用Groovy字符串插值,这是Groovy双引号字符串的一个显著特征。或者,如果您想用Java的方式进行操作:

// could use single-quoted strings here
compile("org.springframework:spring-context:" + springVersion)

我不推荐后者,但希望它有助于解释代码不起作用的原因。

或者您可以通过
依赖项中的变量定义lib版本,如下所示:

dependencies {

    def tomcatVersion = '7.0.57'

    tomcat "org.apache.tomcat.embed:tomcat-embed-core:${tomcatVersion}",
           "org.apache.tomcat.embed:tomcat-embed-logging-juli:${tomcatVersion}"
    tomcat("org.apache.tomcat.embed:tomcat-embed-jasper:${tomcatVersion}") {
           exclude group: 'org.eclipse.jdt.core.compiler', module: 'ecj'
    }

}

谢谢你的解决方案Peter,我现在真的可以工作了:)你能帮我理解为什么它在spring mvc和spring测试工件上失败了吗?我认为Gradle/Groovy让单引号字符串的行为不同于双引号字符串是一个难以置信的坏主意。有什么原因吗?Groovy中有许多不同的字符串文字(不仅仅是两种),与其他动态语言类似。格雷德尔无法控制这一切。至于为什么决定单引号字符串按字面解释
$
,而不支持字符串插值,我不知道答案。如果这对你很重要,也许可以在Groovy邮件列表上查询。非常感谢Peter。这是难以置信的难以找到(谷歌搜索了20多分钟)。非常感激这对我来说不起作用,直到我意识到我使用的是单引号字符串,而插值只适用于双引号字符串。