Gradle fat jar 不包含库

Har*_*own 5 java jar gradle gradle-task fatjar

我创建了一个简单的 Gradle Java 项目。该build.gradle文件如下所示:

plugins {
    id 'java'
}

repositories {
    mavenCentral()
}

dependencies {
    implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.10'
    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.6.0'
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.6.0'
}

test {
    useJUnitPlatform()
}

task customFatJar(type: Jar) {
    archiveBaseName = 'fat-jar'
    from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
    with jar
}
Run Code Online (Sandbox Code Playgroud)

我正在jar根据https://www.baeldung.com/gradle-fat-jar创建脂肪。

但是,生成的 jar 不包含commons-lang3库。它只包含项目的类文件。

为什么我的库没有包含在 fat 中jar

Bjø*_*ter 5

Baeldung 的指南已经过时。我建议按照官方用户指南中的指南进行操作:https : //docs.gradle.org/current/userguide/building_java_projects.html#sec : java_packaging

他们目前建议这样做:

task uberJar(type: Jar) {
    archiveClassifier = 'uber'

    from sourceSets.main.output

    dependsOn configurations.runtimeClasspath
    from {
        configurations.runtimeClasspath.findAll { it.name.endsWith('jar') }.collect { zipTree(it) }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您不喜欢使用像archiveClassifier.

如果您对 Baeldung 版本为何不适合您感兴趣,那是因为它们从名为compile. 您正在使用较新的implementation,因此compile是空的。但是,不是简单地更改compileimplementation,而是建议使用runtimeClasspath(如在用户指南中),因为这将正确处理仅作用于编译阶段或仅作为运行时的依赖项。虽然您现在没有任何这些,但将来可能会有。