依赖包冲突,Error creating bean

启动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,那么这个办法也不可行。

如果对于以上问题您有和妙招或想法,期待能与您交流学习。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值