簡體   English   中英

如何創建包含所有 Maven 依賴項的不可執行 JAR 文件

[英]How to create a non-executable JAR file that includes all Maven dependencies

我有一個 Java 項目,它沒有主文件,但它有很多 Maven 依賴項。

如何創建包含我的源代碼和所需的 maven 依賴項的 JAR 文件?

我的 pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>NetworkCommunicationAPI</groupId>
    <artifactId>NetworkCommunicationAPI</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <build>
        <sourceDirectory>src</sourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <configuration>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
      <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20210307</version>
        </dependency>
    </dependencies>
</project>

您可以使用 Maven 陰影插件或 Maven 組裝插件來創建這樣的 JAR。

在大多數情況下,應避免使用此類 JARs。 您為使用 JAR 的每個人創建了一個依賴地獄,因為 Maven 無法再管理包含的依賴項,因此與其他依賴項(不是來自您的 JAR)的沖突可能變得難以管理。

On the other, such fat JARs are of little use because Maven or Gradle will find your transitive dependencies anyway, so there is no need to include them into the JAR.

您可以使用 maven-assembly-plugin 就像您可以使用它來創建帶有 dependencies 的可執行 JAR 一樣

您唯一需要更改的是您不需要指定主要的 class:

<build>
  <plugins>
    <plugin>
      <artifactId>maven-assembly-plugin</artifactId>
      <configuration>
        <descriptorRefs>
          <descriptorRef>jar-with-dependencies</descriptorRef>
        </descriptorRefs>
      </configuration>
    </plugin>
  </plugins>
</build>

之后,您可以使用mvn compile assembly:single創建 JAR。

這將編譯您的源代碼並創建一個 JAR,其中包含已編譯的源代碼和編譯范圍內的所有依賴項。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM