Spark 3.4.0经Maven编译正常但运行报错,疑Scala版本兼容问题
解决方案:Scala/Spark Maven编译运行版本冲突问题
核心原因
java.lang.NoSuchMethodError 本质是编译时依赖的Scala版本与运行时类路径中的Scala版本不匹配,Maven依赖树里存在多版本Scala构件冲突,导致运行时找不到Scala 2.13.x特有的scala.package$.Seq()方法(Scala 2.13对Seq的实现做了调整,和旧版本不兼容)。
具体修复步骤
1. 强制统一所有Scala依赖版本
在pom.xml中添加dependencyManagement块,锁死所有Scala相关依赖的版本为2.13.8,杜绝依赖传递带来的版本混乱:
<dependencyManagement> <dependencies> <!-- 强制Scala核心库版本 --> <dependency> <groupId>org.scala-lang</groupId> <artifactId>scala-library</artifactId> <version>2.13.8</version> </dependency> <dependency> <groupId>org.scala-lang</groupId> <artifactId>scala-reflect</artifactId> <version>2.13.8</version> </dependency> <dependency> <groupId>org.scala-lang</groupId> <artifactId>scala-compiler</artifactId> <version>2.13.8</version> </dependency> <!-- 强制Spark依赖的Scala版本匹配 --> <dependency> <groupId>org.apache.spark</groupId> <artifactId>spark-core_2.13</artifactId> <version>3.4.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.spark</groupId> <artifactId>spark-sql_2.13</artifactId> <version>3.4.0</version> <scope>provided</scope> </dependency> </dependencies> </dependencyManagement>
2. 排查并清理冲突依赖
运行Maven命令扫描依赖树,定位引入旧版本Scala的第三方依赖:
mvn dependency:tree -Dverbose -Dincludes=org.scala-lang
找到冲突依赖后,在对应<dependency>块中添加排除规则,比如:
<dependency> <groupId>第三方依赖groupId</groupId> <artifactId>第三方依赖artifactId</artifactId> <version>xxx</version> <exclusions> <exclusion> <groupId>org.scala-lang</groupId> <artifactId>scala-library</artifactId> </exclusion> </exclusions> </dependency>
3. 匹配Scala插件版本
确保pom.xml中的Scala编译插件版本和2.13.8兼容,推荐用4.6.2及以上版本:
<build> <plugins> <plugin> <groupId>org.scala-tools</groupId> <artifactId>maven-scala-plugin</artifactId> <version>4.6.2</version> <executions> <execution> <goals> <goal>compile</goal> <goal>testCompile</goal> </goals> </execution> </executions> <configuration> <scalaVersion>2.13.8</scalaVersion> </configuration> </plugin> </plugins> </build>
4. 打包时排除Scala核心库
Spark集群环境自带Scala库,打包时不要把scala-library打入JAR包。如果用Shade插件打包,添加排除规则:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>3.4.1</version> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> <filters> <filter> <artifact>org.scala-lang:scala-library</artifact> <excludes> <exclude>**/*</exclude> </excludes> </filter> </filters> </configuration> </execution> </executions> </plugin>
5. 验证运行时类路径
提交任务时用--verbose参数查看运行时类路径,确认只有Spark自带的和指定的2.13.8版本Scala库:
spark-submit --verbose --class 你的主类名 你的JAR包路径.jar
验证流程
- 执行
mvn clean compile,确认无Scala版本冲突警告 - 打包后用
spark-submit运行,检查是否还出现NoSuchMethodError
内容的提问来源于stack exchange,提问作者Mich Talebzadeh
相关产品推荐
相关产品推荐

