You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无IDE环境下如何用Maven打包含本地外部库的可执行Jar包?

解决Maven打包可执行Jar无法加载外部依赖的问题

问题根源

你使用了<scope>system</scope>的依赖配置,Maven默认不会将这类本地系统依赖复制到项目输出目录(如target/libs)。虽然maven-jar-plugin在Manifest中配置了classpath指向libs/testlib.jar,但实际这个Jar并没有被自动复制到对应目录,导致运行时找不到TEST.Lib类,进而无法执行外部方法。


解决方案

方案1:将本地Jar安装到Maven本地仓库(推荐,符合Maven规范)

把自定义的testlib.jar纳入Maven依赖管理体系,去掉system scope配置:

  1. 执行以下命令将本地Jar安装到Maven本地仓库:
mvn install:install-file -Dfile=libs/testlib.jar -DgroupId=testlib -DartifactId=testlib -Dversion=1.0 -Dpackaging=jar
  1. 修改pom.xml中的依赖配置,删除system和systemPath属性:
<dependency>
  <groupId>testlib</groupId>
  <artifactId>testlib</artifactId>
  <version>1.0</version>
</dependency>
  1. 添加maven-dependency-plugin插件,自动复制依赖到输出目录:
<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-dependency-plugin</artifactId>
  <version>3.6.0</version>
  <executions>
    <execution>
      <id>copy-dependencies</id>
      <phase>package</phase>
      <goals>
        <goal>copy-dependencies</goal>
      </goals>
      <configuration>
        <outputDirectory>${project.build.directory}/libs</outputDirectory>
      </configuration>
    </execution>
  </executions>
</plugin>
  1. 执行mvn clean package打包,target目录下会生成主Jar和包含testlib.jar的libs文件夹,运行主Jar即可正常显示窗口。

方案2:用maven-assembly-plugin打胖Jar(最简易,单Jar运行)

将主类和所有依赖类打包到同一个可执行Jar中,无需额外依赖目录:
在pom.xml中添加插件配置:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-assembly-plugin</artifactId>
  <version>3.6.0</version>
  <configuration>
    <descriptorRefs>
      <descriptorRef>jar-with-dependencies</descriptorRef>
    </descriptorRefs>
    <archive>
      <manifest>
        <mainClass>TEST.App</mainClass>
      </manifest>
    </archive>
  </configuration>
  <executions>
    <execution>
      <id>make-assembly</id>
      <phase>package</phase>
      <goals>
        <goal>single</goal>
      </goals>
    </execution>
  </executions>
</plugin>

执行mvn clean package后,target目录下会生成类似[项目名]-jar-with-dependencies.jar的文件,直接运行该Jar即可正常工作。

方案3:保留system scope,手动复制依赖(不推荐,不符合规范)

如果不想修改依赖配置,可通过插件强制复制system scope依赖:
添加maven-dependency-plugin配置:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-dependency-plugin</artifactId>
  <version>3.6.0</version>
  <executions>
    <execution>
      <id>copy-system-dependencies</id>
      <phase>package</phase>
      <goals>
        <goal>copy-dependencies</goal>
      </goals>
      <configuration>
        <outputDirectory>${project.build.directory}/libs</outputDirectory>
        <includeScope>system</includeScope>
      </configuration>
    </execution>
  </executions>
</plugin>

打包后testlib.jar会被复制到target/libs,此时运行主Jar即可找到依赖类。


内容的提问来源于stack exchange,提问作者YoungUnexpiredMaster

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 05:20:49