提问者:小点点

在JRE容器之前使用Spring Gradle依赖容器会导致编译错误


我正在将一个Java项目从Ant转换为Gradle。我们团队选择的IDE是Eclipse。我已经为Eclipse安装了Spring Gradle插件,应用了Gradle项目性质并启用了依赖管理。结果是一些编译错误。

出现编译错误是因为Gradle依赖容器位于eclipse类路径中JRE容器之前。类路径上的一些jar包含应该来自rt.jar的类(它们与我们的代码不兼容,可能是旧版本)。

当依赖项管理被禁用时,gradle 依赖项出现在 JRE 容器之后,并且编译时没有错误。这也与我使用 Eclipse/Maven/m2e 一致,其中 Maven 依赖容器位于 eclipse 中的 JRE 容器之后。

这是插件的默认行为(将 gradle 容器放在 JRE 之前)吗?有没有办法改变它?

我试图在我的build.gradle中使用eclipse钩子(whenMerged和withXml)来实现这一点,但这些钩子似乎是在gradle依赖项被容器条目替换之前执行的。


共2个答案

匿名用户

对订单有一些控制,但对您来说可能不够精确。右键单击项目并选择“属性”

然后选择一个排序选项,如“按路径字母顺序”。更改此选项后,请执行“Gradle

如果您选择“由BuildScript返回”,我想这一定是您所拥有的。顺序将被颠倒(JRE之前的Gradle)。这里有一个难题,即构建脚本实际上并没有返回“gradle依赖项”容器(仅返回其内容),因此构建脚本并没有真正定义顺序。

不幸的是,您可能有理由选择该选项,并且对容器内的依赖项进行排序实际上可能不是一个可行的解决方案。

如果是这样,您可能还可以尝试第二件事。

导入项目时,导入向导会在“导入选项”下显示“运行时间”。您可以尝试在导入结束时使用指定的任务来修改.classpath文件(它也将在刷新时执行)。

最后最后一个建议。你试过BuildShip吗?也许它对你的项目更有效。

匿名用户

这是我交换容器的代码。这可能有点冗长,原因有几个。1.我是Groovy的新手,来自Java背景。2.Gradle对我自己和团队来说都是新手,我想清楚它在做什么。

// Swap the order of the JRE and classpathcontainer
// https://issuetracker.springsource.com/browse/STS-4332
task afterEclipseImport(description: "Post processing after project generation", group: "IDE") {
    doLast {
        def cp = new XmlParser().parse(file(".classpath"))
        def container
        def cons = cp.classpathentry.findAll { it.@kind == "con" }
        cons.find {
            if (it.@path.equals("org.springsource.ide.eclipse.gradle.classpathcontainer")) {
                println "found Gradle dependency container"
                container = it
            } else if (it.@path.contains("JRE_CONTAINER")) {
                if (container == null) {
                    println "found JRE container before Gradle dependency container, nothing to do"
                    // Return true to end the loop (return by itself is not enough)
                    return true
                }
                println "found JRE container, swap with Gradle dependency container"
                container.replaceNode(it)
                it.replaceNode(container)
                // Return true to end the loop (return by itself is not enough)
                return true
            }
            return false
        }
        def builder = new StreamingMarkupBuilder()
        builder.encoding = "UTF-8"
        file(".classpath").withWriter {writer ->
             writer << builder.bind { mkp.xmlDeclaration() }
             def printer = new XmlNodePrinter(new PrintWriter(writer))
             // println cp
             printer.print(cp)
        }
    }
}