【问题标题】:Build is successful but the runtime dependency seems bad in Gradle dependency构建成功,但运行时依赖在 Gradle 依赖中似乎很糟糕
【发布时间】:2016-01-17 08:28:24
【问题描述】:
dependencies {
 compile 'org.slf4j:slf4j-api:1.7.13'
    compile group: 'org.apache.commons', name: 'commons-math3' , version: '+'
    testCompile 'junit:junit:4.12'
}

即使我添加了这个,当我运行 gradle build 时,它也可以工作,并且可以编译带有 commons-math3 的代码。但是当我在 build/ 中运行一个 jar 文件时,

它说 线程“主”java.lang.NoClassDefFoundError 中的异常:org/apache/commons/math3/complex/Complex

但 Gradle 官方网站说,“编译”中的资源也将包含在“运行时”依赖项中。我还尝试将 commons-math 添加到运行时。但它不起作用。

也许这是我对依赖系统的误解。

如何将 maven 存储库中的外部库包含到 Gradle 生成的 jar 文件中。

【问题讨论】:

  • 如何运行 jar?具体来说,你是如何设置类路径的?

标签: java maven gradle


【解决方案1】:

您要查找的是application 插件生成的分发zip 或shadowJar 插件生成的shadow jar(也称为fat jar):

分发 zip(application 插件)

关于分发 zip

分发 zip 如下所示:

my-app-0.2.0.zip
├──bin
│  ├──my-app
│  └──my-app.bat
└──lib
   ├──my-app-0.2.0.jar
   ├──slf4j-api.1.7.13.jar
   └──commons-math3-3.6.jar

然后您可以通过解压缩在build/distributions/ 中生成的内容并运行my-app.bat(在Windows 上)或./my-app(在Linux 或OS X 上)来运行您的应用程序及其依赖项

构建分发 zip

这是一个用于制作分发 zip 的示例 gradle 构建文件:

build.gradle

apply plugin: 'java'
apply plugin: 'application'

mainClassName = 'org.myapp.Main'

repositories { jcenter() }
dependencies {
    compile 'org.slf4j:slf4j-api:1.7.13'
    compile 'org.apache.commons:commons-math3:3.6'

    testCompile 'junit:junit:4.12'
}

可以使用gradle distributionZipgradle distributionTar 运行。要仅运行应用程序,请使用 gradle run

影子罐

关于影子罐

shadow jar 是一个巨大的 jar 文件,它是您的程序及其库的组合,打包到一个文件中。您将获得一个独立的文件,可以通过在大多数系统上双击来运行(例如,在可以运行的 Windows 上,在 Xubuntu 上,它可以通过右键单击并选择“使用 Oracle Java 8 运行时运行”来运行,等等……)。

构建分发 zip

这里又是一个示例build.gradle 文件:

apply plugin: 'java'
apply plugin: 'com.github.johnrengelman.shadow'

mainClassName = 'org.myapp.Main'

jar {
    manifest {
        attributes('Main-Class': mainClassName)
    }
}

buildscript {
    repositories { jcenter() }
    dependencies {
        classpath 'com.github.jengelman.gradle.plugins:shadow:1.2.2'
    }
}

repositories { jcenter() }
dependencies {
    compile 'org.slf4j:slf4j-api:1.7.13'
    compile 'org.apache.commons:commons-math3:3.6'

    testCompile 'junit:junit:4.12'
}

使用gradle shadowJar 运行它 - 带有打包依赖项的 jar 将位于 build/libs 中,并将命名为 my-app-x.x.x-all.jar

【讨论】:

    【解决方案2】:

    Gradle 首先是一个构建工具(就像 maven,顺便说一句)。 它的“责任”从您向其提供源文件时开始,并在您获得工件(在您的情况下为 jar)时结束。

    现在,当您要实际运行应用程序时,这里有很多不同的选项。 如果你只是运行java -jar <your_jar>,你自己负责构建类路径。 如果您使用某种外部运行器运行它,您应该阅读它的文档并为其提供类路径。

    希望对你有帮助

    【讨论】:

    • 谢谢我从configurations.compile.collect { it.isDirectory() 中添加?它:将 zipTree(it) 放入 'jar'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-30
    • 2016-01-10
    • 1970-01-01
    • 1970-01-01
    • 2014-05-19
    • 2015-11-30
    • 2016-05-30
    相关资源
    最近更新 更多