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/google/gson/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:/C:/Users/gjs/.m2/ctgrepository/com/google/code/gson/gson/2.2.4/gson-2.2.4.jar


Action:

Correct the classpath of your application so that it contains a single, compatible version of com.google.gson.GsonBuilder

解决方法

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>
作者:ki16
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文连接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/gaojinshun/p/14524746.html