一止长渊

容器中同时有两个同类型Bean存在

N 人看过
字数:282字 | 预计阅读时长:1分钟

本文主要介绍容器中同时存在两个同类型的 Bena 解决方法

解决一:对于自己写的两个同类型的 Bean

可以使用@Primary 来标注其中一个 Bean 为主要的

解决二:对于依赖中可能存在两个同类型的 Bean

例如引入 Sentinel 对 Feign 远程调用失败进行熔断返回默认数据,同时又想利用 Sleuth 对服务之间调用链进行追踪方便确认异常所在

Field seckillFeignService in com.lookstarry.doermail.product.service.impl.SkuInfoServiceImpl required a single bean, but 2 were found:
    - feignSentinelBuilder: defined by method 'feignSentinelBuilder' in class path resource [com/alibaba/cloud/sentinel/feign/SentinelFeignAutoConfiguration.class]
    - feignHystrixBuilder: defined by method 'feignHystrixBuilder' in class path resource [org/springframework/cloud/sleuth/instrument/web/client/feign/TraceFeignClientAutoConfiguration.class]

可以发现这两个 Bean 都是继承于 Builder 类,所以造成了同类型冲突
在项目启动类排除其中某个配置类,这里排除 SentinelFeignAutoConfiguration 配置类

@SpringBootApplication(exclude = SentinelFeignAutoConfiguration.class)

对于 Feign 熔断方法仍然可以适用
image.png

解决三:spring 开启允许 Bean 定义重复(实验无效)

spring:
  main:
    allow-bean-definition-overriding: true

需要有依赖 spring-boot-actuator 依赖

本作品采用 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议 (CC BY-NC-ND 4.0) 进行许可。