You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SpringBoot 2.6.4升级后应用启动失败:RestClient多Primary Bean冲突

解决Spring 2.6.4升级后多个@Primary Bean导致的自动装配冲突问题

你的问题核心是Spring容器中存在多个标注了@Primary的com.mycomp.api.core.web.util.RestClient类型Bean,触发了Spring 2.6.x版本严格的Bean优先级校验,导致自动装配时无法确定唯一候选Bean,最终引发BGMRequestsController等Bean的依赖注入失败,应用启动异常。

以下是几种可行的解决方法:

  • 清理冗余的@Primary注解
    逐一检查所有实现RestClient的Bean(BGMRequestsGatewayImpl、getRestClientUtil、restClientBean、serviceMeshRestClient),只保留一个你实际需要作为默认优先候选的Bean上的@Primary注解,其余全部移除。比如如果当前环境下serviceMeshRestClient是主要使用的实现,就仅给它保留@Primary。

  • 用@Qualifier指定具体注入的Bean
    如果必须保留多个RestClient类型Bean且不想调整@Primary,可以在依赖注入的位置通过@Qualifier明确指定要使用的Bean名称:

    @Autowired
    @Qualifier("serviceMeshRestClient") // 替换为目标Bean的名称
    private RestClient restClient;
    

    构造函数注入的写法示例:

    private final RestClient restClient;
    
    public BGMRequestsController(@Qualifier("serviceMeshRestClient") RestClient restClient) {
        this.restClient = restClient;
    }
    
  • 限制Bean的加载范围(可选)
    若某些RestClientBean并非当前应用所需,可以通过调整@ComponentScan的排除规则,或者在对应的配置类上添加@Conditional系列注解(比如@ConditionalOnProperty),让Spring只加载需要的Bean,从根源避免冲突。

注意:Spring 2.6.x版本对Bean优先级的校验比旧版本更严格,之前可能存在多个@Primary但未报错的情况,升级后会直接抛出启动异常,所以必须明确Bean的优先级或指定具体注入对象。

内容的提问来源于stack exchange,提问作者KVL

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 18:15:16