java 程序化创建Fat-Jar

vhipe2zx  于 2023-10-14  发布在  Java
关注(0)|答案(1)|浏览(104)

我正在尝试以编程方式创建一个fat-jar。到目前为止,我设法创建了一个Jar文件,里面有我的代码。问题是,如果我运行这个,我会收到一个异常,写着Cannot load user class: org.company.bla.bla
这是我的代码

private static void createJar() throws IOException {

        Manifest manifest = new Manifest();
        manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
        JarOutputStream target = new JarOutputStream(new FileOutputStream("events.jar"), manifest);

        Path root = Paths.get(".").normalize().toAbsolutePath();
        System.out.println(root.toString());

        Files.walk(root).forEach(f -> add(f.toFile(), target));

        target.close();
    }

    private static void add(File source, JarOutputStream target)
    {
        BufferedInputStream in = null;
        try {
            if (source.isDirectory()) {
                String name = source.getPath().replace("\\", "/");
                if (!name.isEmpty()) {
                    if (!name.endsWith("/"))
                        name += "/";
                    JarEntry entry = new JarEntry(name);
                    entry.setTime(source.lastModified());
                    target.putNextEntry(entry);
                    target.closeEntry();
                }
                for (File nestedFile: source.listFiles())
                    add(nestedFile, target);
                return;
            }

            JarEntry entry = new JarEntry(source.getPath().replace("\\", "/"));
            entry.setTime(source.lastModified());
            target.putNextEntry(entry);
            in = new BufferedInputStream(new FileInputStream(source));

            byte[] buffer = new byte[1024];
            while (true) {
                int count = in.read(buffer);
                if (count == -1)
                    break;
                target.write(buffer, 0, count);
            }
            target.closeEntry();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

我如何将依赖项也添加到这个Jar?或者依赖项所在的路径在哪里,以便我可以包含它们?

h6my8fg2

h6my8fg21#

创建一个Uber / Shadow对象意味着Maven或Gradle也可以用来处理所有的库依赖关系。
如果是这样,一个解决方案是从Java运行Maven或Gradle构建命令行arg(使用Runtime.exec()命令)。
以编程方式执行此操作的一个用例是作为Java集成测试的一部分,其中需要Uber Jar(参见Testing custom Kafka Connect SMT using Test Containers的示例)。
以下解决方案同时支持Gradle / Maven。

Maven

确保pom.xml包含Maven Shade Plugin插件,例如:

<?xml version="1.0" encoding="UTF-8"?>
<project>
    <modelVersion>4.0.0</modelVersion>

    <groupId>test</groupId>
    <artifactId>helloworld</artifactId>
    <version>1.0</version>
    <packaging>jar</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <jdk.version>1.11</jdk.version>
        <maven.compiler.plugin.version>3.8.1</maven.compiler.plugin.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.13.0</version>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>5.8.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>5.8.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.assertj</groupId>
            <artifactId>assertj-core</artifactId>
            <version>3.24.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.5.1</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

在项目中安装Maven wrapper也很有用(例如,运行mvn wrapper:wrapper)。
要测试,请运行./mvnw package.

$ ./mvnw package

[INFO] Scanning for projects...
...
[INFO] Replacing original artifact with shaded artifact.
[INFO] Replacing /Users/bobmarks/code/test/fatjar/target/helloworld-1.0.jar with /Users/bobmarks/code/test/fatjar/target/helloworld-1.0-shaded.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  1.129 s
[INFO] Finished at: 2023-10-12T12:05:04+01:00
[INFO] ------------------------------------------------------------------------

...并确保文件存在于target文件夹中:

$ ls -al target/*.jar 

-rw-r--r--@ 1 user  group  1336348 Oct 12 12:05 target/helloworld-1.0.jar
-rw-r--r--@ 1 user  group     1675 Oct 12 12:05 target/original-helloworld-1.0.jar

请注意,较大的文件(helloworld-1.0.jar)是Uber Jar。

Gradle

对于Gradle,我们应该确保Gradle Shadow插件存在于build.gradle文件的plugins部分,例如:

plugins {
    id("com.github.johnrengelman.shadow") version "6.0.0"
}

apply plugin: 'java'

java {
    sourceCompatibility = 1.11
    targetCompatibility = 1.11
}

repositories {
    mavenCentral()
}

test {
    useJUnitPlatform()
}

dependencies {
    implementation 'org.apache.commons:commons-lang3:3.13.0'

    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.0'
    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.0'
    testImplementation 'org.assertj:assertj-core:3.24.2'
}

还有settings.gradle

rootProject.name = 'helloworld'

另外,Gradle wrapper(例如,运行gradle wrapper)。
要测试,请运行./gradlew shadowJar...

$ ./gradlew shadowJar

BUILD SUCCESSFUL in 554ms
2 actionable tasks: 1 executed, 1 up-to-date

...并确保文件存在于build/libs文件夹中:

$ ls -al build/libs/*.jar 

-rw-r--r--@ 1 user  group  632280 Oct 12 12:39 build/libs/helloworld-all.jar

使用Java创建Jar文件

创建UberJars的代码如下:

import java.io.IOException;
import java.util.Scanner;

public class UberJar {

    public static void createUberJarMaven() {
        createUberJar("mvnw.cmd", "./mvnw", "package -DskipTests", "BUILD SUCCESS");
    }

    public static void createUberJarGradle() {
        createUberJar("gradlew.bat", "./gradlew", "shadowJar", "BUILD SUCCESSFUL");
    }

    private static void createUberJar(String cmdWindows, String cmdLinux, String cmdBuild, String outputSuccess) {
        String cmd = isWindows() ? cmdWindows : cmdLinux;
        String output = execCmd(cmd + " " + cmdBuild);
        if (output == null || !output.contains(outputSuccess)) {
            throw new RuntimeException("Ubar JAR creation unsuccessful\n\n" + output);
        }
    }

    private static String execCmd(String cmd) {
        try {
            Scanner s = new Scanner(Runtime.getRuntime().exec(cmd).getInputStream()).useDelimiter("\\A");
            return s.hasNext() ? s.next() : "";
        } catch (IOException ioEx) {
            throw new RuntimeException("Error executing: " + cmd, ioEx);
        }
    }

    private static boolean isWindows() {
        return System.getProperty("os.name").toLowerCase().startsWith("windows");
    }

}

测试这两种情况的单元测试如下:

import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.io.File;
import static org.assertj.core.api.Assertions.assertThat;

public class UbarJarTest {

    private static final File MAVEN_UBER_FILE = new File("target/helloworld-1.0.jar");
    private static final File GRADLE_UBER_FILE = new File("build/libs/helloworld-all.jar");

    @BeforeAll
    public static void setup() {
        if (MAVEN_UBER_FILE.exists()) {
            MAVEN_UBER_FILE.delete();
        }
        if (GRADLE_UBER_FILE.exists()) {
            GRADLE_UBER_FILE.delete();
        }
    }

    @Test
    public void should_create_uber_jar_maven() {
        assertThat(MAVEN_UBER_FILE).doesNotExist();

        UberJar.createUberJarMaven();

        assertThat(MAVEN_UBER_FILE).exists();
    }

    @Test
    public void should_create_uber_jar_gradle() {
        assertThat(GRADLE_UBER_FILE).doesNotExist();

        UberJar.createUberJarGradle();

        assertThat(GRADLE_UBER_FILE).exists();
    }

}

相关问题