在 fat JAR 中包含源

Gab*_*yas 5 jar gradle shadowjar

我将 Gradle 用于一个简单的 Java 项目,并希望生成一个单一的 fat JAR,其中也包含源代码。

\n\n

我在以下位置准备了一个示例存储库: https: //github.com/szarnyasg/gradle-shadowjar-source。我尝试了这个build.gradle配置:

\n\n
plugins { id "com.github.johnrengelman.shadow" version "1.2.4" }\n\napply plugin: \'java\'\n\nshadowJar {\n    classifier = \'fat\'\n    manifest { attributes \'Main-Class\': \'org.example.MyMain\' }\n}\n\ntask packageSources(type: Jar) {\n    from sourceSets.main.allSource\n}\n\nartifacts.archives packageSources\n
Run Code Online (Sandbox Code Playgroud)\n\n

我可以用以下方法构建它:

\n\n
./gradlew clean build shadowjar\n
Run Code Online (Sandbox Code Playgroud)\n\n

这会在目录中产生两个 JAR 文件build/libs

\n\n
    \n
  • example-fat.jar- 没有来源的胖 JAR
  • \n
  • example.jar- 一个包含(仅)源代码的 JAR
  • \n
\n\n

Gradle Shadow 插件的文档指出

\n\n
\n

java在存在或插件的情况下groovy,Shadow 将自动配置以下行为:

\n\n

[...]

\n\n
    \n
  • 配置shadowJar任务以包含项目\xe2\x80\x99s 主源集中的所有源。
  • \n
\n
\n\n

对我来说,这意味着源代码包含在生成的 JAR 中,但这可能不是它的意思。

\n\n

是否可以从 Gradle 生成可执行的 fat JAR,其中也包含源代码?

\n

JBi*_*gas 1

我不是 100% 确定如何shadowJar处理源,但您可以推出自己的 fat jar 实现。

apply plugin: 'groovy'

repositories {
    jcenter()
}

version = "0.1"
group = "com.jbirdvegas.so"

dependencies {
    // some dependencies to show the use case
    compile localGroovy(), 'org.slf4j:slf4j-api:1.7.21', 'org.slf4j:slf4j-simple:1.7.21'
    testCompile 'junit:junit:4.12'
}

jar {
    // set manifest
    manifest.attributes 'Implementation-Title': 'Executable fat jar',
            'Implementation-Version': version,
            'Main-Class': 'com.jbirdvegas.q40744642.Hello'
}

task fatJar(type: Jar) {
    // baseName must be unique or it clashes with the default jar task output
    baseName = "$project.name-fat"
    // make sure you have a valid manifest
    manifest = jar.manifest
    // Here put the source output (class) files in the jar
    // as well as dependencies (jar) files.
    from sourceSets.main.output,
            configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
}

// make sure our fatJar always runs immediately after the jar task
jar.finalizedBy fatJar
Run Code Online (Sandbox Code Playgroud)

现在,在 jar 任务执行后,我们就有了一个准备就绪的可执行 jar

$ java -jar build/libs/q40744642-fat-0.1.jar 
[main] INFO com.jbirdvegas.q40744642.Hello - Hello World!
Run Code Online (Sandbox Code Playgroud)

为了完整起见,这是我的Hello.groovy课程

package com.jbirdvegas.q40744642

import org.slf4j.Logger
import org.slf4j.LoggerFactory

class Hello {
    static main(args) {
        Logger logger = LoggerFactory.getLogger(Hello.class)
        logger.info("Hello World!")
    }
}
Run Code Online (Sandbox Code Playgroud)