如何使用 Maven 创建具有依赖关系的可执行 JAR?

我想将我的项目打包到一个可执行的 JAR 中进行分发.

I want to package my project in a single executable JAR for distribution.

如何让一个 Maven 项目将所有依赖 JAR 打包到我的输出 JAR 中?

How can I make a Maven project package all dependency JARs into my output JAR?

推荐答案

<build>
  <plugins>
    <plugin>
      <artifactId>maven-assembly-plugin</artifactId>
      <configuration>
        <archive>
          <manifest>
            <mainClass>fully.qualified.MainClass</mainClass>
          </manifest>
        </archive>
        <descriptorRefs>
          <descriptorRef>jar-with-dependencies</descriptorRef>
        </descriptorRefs>
      </configuration>
    </plugin>
  </plugins>
</build>

然后你运行它

mvn clean compile assembly:single

编译目标应该在汇编之前添加:single否则不包括你自己项目上的代码.

在评论中查看更多详细信息.

See more details in comments.

通常,此目标与自动执行的构建阶段相关联.这可确保在执行 mvn install 或执行部署/发布时构建 JAR.

Commonly this goal is tied to a build phase to execute automatically. This ensures the JAR is built when executing mvn install or performing a deployment/release.

<build>
  <plugins>
    <plugin>
      <artifactId>maven-assembly-plugin</artifactId>
      <configuration>
        <archive>
          <manifest>
            <mainClass>fully.qualified.MainClass</mainClass>
          </manifest>
        </archive>
        <descriptorRefs>
          <descriptorRef>jar-with-dependencies</descriptorRef>
        </descriptorRefs>
      </configuration>
      <executions>
        <execution>
          <id>make-assembly</id> <!-- this is used for inheritance merges -->
          <phase>package</phase> <!-- bind to the packaging phase -->
          <goals>
            <goal>single</goal>
          </goals>
        </execution>
      </executions>
    </plugin>
  </plugins>
</build>

相关文章