启动Spring项目失败,日志提示Error creating bean with name ‘gsonBuilder’ defined in class path resource
这里是在提醒创建在类路径资源中定义了名为“gsonBuilder”的bean时出错,通常是gsonBuilder这个依赖包有冲突,比如你pom导入的依赖包下,有子依赖包与Spring的子依赖包重复时,就会抛出这个错误,根据类路径资源导入bean时抛出了这个错误。
笔者完整抛错如下:
2021-04-14 23:33:38.479 WARN 17528 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: 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;
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-04-14 23:33:38.730 ERROR 17528 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
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;
这时有两种解决办法
一、删除冲突的依赖包
比如笔者是因为com.tencentcloudapi下的子依赖包.code.gson与spring下的.code.gson冲突
<dependency>
<groupId>com.tencentcloudapi</groupId>
<artifactId>tencentcloud-sdk-java</artifactId>
<version>4.0.11</version>
<exclusions>
<exclusion>
<artifactId>gson</artifactId>
<groupId>com.google.code.gson</groupId>
</exclusion>
</exclusions>
</dependency>
如此项目启动时不会再冲突,但存在隐患,如果在使用tencentcloudapi时需要用到gson中的方法时,就会抛错找不到依赖包。
二、替换依赖包
当出现第一中办法所面临的问题时,可以将冲突的依赖包直接在pom中maven方式导入,如此项目既能正常启动又不影响tencentcloudapi的功能。
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
这两种方法都有它们的局限性,第一个方法容易影响你引入的依赖的功能,而第二种方法要求冲突的包可以通过maven导入。且冲突的包是功能相同的包,例如笔者冲突的gson,如果spring不能兼容使用com.google.code.gson,或tencentcloudapi下导入的是其他com…gson,那么这个办法也不可行。
如果对于以上问题您有和妙招或想法,期待能与您交流学习。