SpringBoot 引入第三方包之后 报错 java.lang.NoSuchMethodError: com.google.gson.GsonBuilder.setLenient()
背景
在使用 powerjob 时引入第三方 jar 包(odps)后 SpringBoot 启动报错
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'gsonBuilder' defined in class path resource [org/springframework/boot/autoconfigure/gson/GsonAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.google.gson.GsonBuilder]: Factory method 'gsonBuilder' threw exception; nested exception is java.lang.BootstrapMethodError: java.lang.NoSuchMethodError: com.google.gson.GsonBuilder.setLenient()Lcom/google/gson/GsonBuilder;
Description:
An attempt was made to call a method that does not exist. The attempt was made from the following location:
java.lang.invoke.MethodHandleNatives.resolve(Native Method)
The following method did not exist:
com.google.gson.GsonBuilder.setLenient()Lcom</span>/google/gson/<span style="color: rgba(0, 0, 0, 1)">GsonBuilder;
The method's class, com.google.gson.GsonBuilder, is available from the following locations:
jar:file:/C:/Users/gjs/.m2/ctgrepository/com/google/code/gson/gson/2.2.4/gson-2.2.4.jar!/com/google/gson/GsonBuilder.class
It was loaded from the following location:
file:</span>/C:/Users/gjs/.m2/ctgrepository/com/google/code/gson/gson/2.2.4/gson-2.2.4<span style="color: rgba(0, 0, 0, 1)">.jar
Action:
Correct the classpath of your application so that it contains a single, compatible version of com.google.gson.GsonBuilder
解决方法
1 2 | The following method did not exist: com.google.gson.GsonBuilder.setLenient()Lcom/google/gson/GsonBuilder; |
报错信息中提示找不到 GsonBuilder 的 setLenient() 方法,很明显是 jar 包版本冲突了,gson 版本太低了
可以去 maven 仓库查看 SpringBoot 所需对应的 gson 版本
https://mvnrepository.com/artifact/org.springframework.boot/spring-boot
我使用的 SpringBoot 版本是 2.2.6.RELEASE
SpringBoot 2.2.6.RELEASE 需要使用 2.8.6 以上的 gson,而引入的 odps 依赖的是 2.2.4
一般 jar 包都可以向上兼容,所以直接在 pom 文件中直接引入 2.8.6 以上的 gson 替换即可,不需要去改变 odps 的版本
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.6</version> </dependency>