The bean ‘XX‘, could not be registered. A bean with that name has already been defined in null and

问题

在这里插入图片描述

英文:The bean ‘1.FeignClientSpecification’, defined in null, could not be registered. A bean with that name has already been defined in null and overriding is disabled.

中文:定义为null的FeignClientSpecification’无法注册。具有该名称的bean已经被定义为null,并且禁止重写。

原因

先解释注解@FeignClient

主要属性:

  1. name (或 value):
    • 服务名称,用于服务发现(当使用 Eureka 等注册中心时)
    • 必须属性
  2. url:
    • 直接指定服务的 URL(绕过服务发现)
    • 当不使用服务发现时使用
  3. contextId:
    • 在同一应用中定义多个相同名称的 Feign 客户端时使用

分析

默认情况下,Spring 会根据 @FeignClient 的 name 或 value 属性来注册 Feign 客户端 Bean。
但如果同一个应用中定义了多个相同name的 Feign 客户端,Spring 会报错,因为 Bean 名称冲突。

所以原因就是因为出现了多个同名的Bean。

如果spring对同一个包扫描了多次,即使只有一个FeignClient也会报错,因为在第二次扫描创建的之前第一次已经创建了。

解决

方法1

为相同的Bean指定不同的contextId,contextId 允许我们为同一个name的 Feign 客户端指定不同的上下文标识符,从而避免 Bean 名称冲突

@FeignClient(name = "user-service", contextId = "client1")  // 使用 contextId 区分
public interface UserServiceClient1 {
    @GetMapping("/users/{id}")
    User getUserById(@PathVariable Long id);
}

@FeignClient(name = "user-service", contextId = "client2")  // 使用不同的 contextId
public interface UserServiceClient2 {
    @GetMapping("/users/{id}")
    User getUserById(@PathVariable Long id);
}
  • 这样,Spring 会注册两个不同的 Feign 客户端 Bean,名称分别为:
    • user-service.client1(对应 UserServiceClient1)
    • user-service.client2(对应 UserServiceClient2)

方法2

找出重复扫描的问题。

方法3

报错的地方也给了提示Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true,可以配置,覆盖Bean的方式,如果覆盖没问题就可以用。

main:
	allow-bean-definition-overriding: true
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值