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

Maven中TestNG的test依赖引入Guava进入Fat Jar问题咨询

问题原因解析

1. maven-assembly-plugin的默认打包逻辑

maven-assembly-plugin的默认配置不会自动过滤test作用域的依赖,它会把所有依赖(包括test范围)及其传递依赖都打包进Fat Jar里。哪怕TestNG是test作用域,只要没做特殊配置,它带的Guava传递依赖也会被包含进去。

2. Maven依赖版本的优先级规则

Maven依赖解析遵循两个核心规则:

  • 最短路径优先:如果TestNG到Guava的依赖路径比protobuf-java-util到Guava的路径更短,TestNG引入的Guava版本会被优先选中。
  • 声明顺序优先:如果TestNG在根pom里的声明位置早于protobuf-java-util,它的Guava版本也会被优先解析。
    只要TestNG的Guava被打包进Jar,运行时就会加载这个版本,覆盖protobuf-java-util引入的版本。

3. mvn:dependency-tree的显示逻辑

mvn dependency:tree默认会展示所有作用域的依赖,包括test范围。当你排除TestNG的Guava后,test作用域的这条依赖链被移除,自然就只显示protobuf-java-util引入的Guava版本了。

解决建议

  • 配置assembly过滤test依赖:在assembly的descriptor文件里指定只打包runtime作用域的依赖,彻底排除test范围的依赖:
    <dependencySets>
      <dependencySet>
        <scope>runtime</scope>
        <unpack>true</unpack>
      </dependencySet>
    </dependencySets>
    
  • 直接排除TestNG的Guava传递依赖:在根pom的TestNG依赖中添加排除规则,从根源避免版本冲突:
    <dependency>
      <groupId>org.testng</groupId>
      <artifactId>testng</artifactId>
      <version>你的TestNG版本</version>
      <scope>test</scope>
      <exclusions>
        <exclusion>
          <groupId>com.google.guava</groupId>
          <artifactId>guava</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 02:34:54