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

Maven编译时保留外部Jar依赖,构建Fat Jar时排除该依赖的解决方案咨询

没问题,我给你几个适配你场景的解决方案——既能保留这个外部Jar用于编译,又不会把它打包进Fat Jar,而且完全不需要把Jar传到本地Maven仓库,适合Jenkins环境:

方案1:在maven-assembly-plugin中排除指定依赖

既然你用了maven-assembly-plugin的jar-with-dependencies描述符,直接在插件配置里添加排除规则即可,精准过滤掉这个system依赖:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-assembly-plugin</artifactId>
  <version>3.2.0</version>
  <configuration>
    <descriptorRefs>
      <descriptorRef>jar-with-dependencies</descriptorRef>
    </descriptorRefs>
    <!-- 添加排除规则,匹配你的外部Jar的groupId和artifactId -->
    <exclusions>
      <exclusion>
        <groupId>a.b.c</groupId>
        <artifactId>xyz</artifactId>
      </exclusion>
    </exclusions>
  </configuration>
  <executions>
    <execution>
      <id>assemble-all</id>
      <phase>package</phase>
      <goals>
        <goal>single</goal>
      </goals>
    </execution>
  </executions>
</plugin>

方案2:在maven-shade-plugin中配置过滤规则

如果你主要用maven-shade-plugin构建Fat Jar,同样可以在插件的执行配置里添加过滤,排除这个依赖的所有内容:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-shade-plugin</artifactId>
  <version>3.1.1</version>
  <executions>
    <execution>
      <phase>package</phase>
      <goals>
        <goal>shade</goal>
      </goals>
      <configuration>
        <filters>
          <filter>
            <!-- 匹配你的外部Jar坐标 -->
            <artifact>a.b.c:xyz</artifact>
            <excludes>
              <!-- 排除该Jar下所有文件 -->
              <exclude>**/*</exclude>
            </excludes>
          </filter>
        </filters>
      </configuration>
    </execution>
  </executions>
</plugin>

方案3:修改依赖的Scope为provided(最简洁)

这是最省事的方法——把依赖的scope从system改成provided,同时保留systemPath。Maven的provided scope表示该依赖仅用于编译和测试阶段,运行时由外部环境提供,因此不会被打包进任何Jar(包括Fat Jar):

<dependency>
  <groupId>a.b.c</groupId>
  <artifactId>xyz</artifactId>
  <version>1.0</version>
  <scope>provided</scope>
  <systemPath>${project.basedir}/lib/library.jar</systemPath>
</dependency>

注意事项

  • 确保Jenkins构建环境中,${project.basedir}/lib/library.jar路径是可访问的——建议把lib目录和项目代码一起纳入版本控制,或者在Jenkins构建脚本中提前拉取这个Jar到指定位置。
  • 如果同时使用assembly和shade两个插件,建议只保留一个用来构建Fat Jar,避免重复打包或冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 04:07:47