清茶书香

一杯清茶,一本书籍,一个下午。


  • 首页

  • 归档

  • 分类

  • 关于

  • 搜索
Redis JPA Solr SpringData SpringMVC localRepository local Mapper 事务 Mybatis JDBC AOP DI IOC 常用函数 触发器 存储过程 Promise Gateway SpringCloud vue-cli axios es6 webpack npm vue 个性化 zsh 终端 caffeine jvm缓存 guava cache validation Mapping MapStruct comment 小程序 建站 WeHalo config logback plugins database idea maven spring https http nginx password RabbitMQ 秒杀系统 Windows MySQL 数据备份 halo SpringBoot shell Linux ip Optional Stream Lambda k8s Docker 列编辑 vim MacOS 图片合成 Java 远程联调 nps 内网穿透

spring-cloud-gateway注入Bean时循环依赖

发表于 2021-05-08 | 分类于 spring系列 | 0 | 阅读次数 1797

在spring-cloud-gateway中自动注入一个Bean出现循环依赖的问题解决方案:

先给出解决方案:

@Autowired
private ObjectProvider<T> objectProvider;

objectProvider.getIfAvailable().getSomeFunction();

这是我在spring-cloud-openfegin的官方issue中找到的一个方案,我选择的是这种方式解决。

另一种是在其他开源项目的issue中找到的大佬解决方案(SpringUtils非官方Util,仅提供思路):

DemoService bean = SpringUtils.getBean(DemoService.class);

问题报错内容:

***************************
APPLICATION FAILED TO START
***************************

Description:

The dependencies of some of the beans in the application context form a cycle:

   demoGatewayFilterFactory (field private com.bennett.gateway.client.DemoClient com.bennett.gateway.filter.DemoGatewayFilterFactory.demoClient)
┌─────┐
|  com.bennett.gateway.client.DemoClient
↑     ↓
|  cachedCompositeRouteLocator defined in class path resource [org/springframework/cloud/gateway/config/GatewayAutoConfiguration.class]
↑     ↓
|  routeDefinitionRouteLocator defined in class path resource [org/springframework/cloud/gateway/config/GatewayAutoConfiguration.class]
↑     ↓
|  demo2GatewayFilterFactory (field private com.bennett.gateway.client.DemoClient com.bennett.gateway.filter.Demo2GatewayFilterFactory.demoClient)
└─────┘

我在两个自定义过滤器中注入了同一个Bean,也就是一个FeginClient的接口。这与注入一个任意的Bean是一样的,也就是说注入其他类型的Bean也是会出现这种问题的。这种由框架本身引起的依赖循环可以用这种方式解决,但若是自己项目引发的问题建议优化下代码,避免两个类之间过度耦合。

Bennett wechat
欢迎收藏我的微信小程序,方便查看更新的文章。
  • 本文作者: Bennett
  • 本文链接: https://hibennett.cn/archives/inject-bean-cause-cycle-dependency
  • 版权声明: 本博客所有文章除特别声明外,均采用CC BY-NC-SA 3.0 许可协议。转载请注明出处!
# Java # spring # SpringCloud # Gateway
vue学习记录之vue-cli
Spring Boot中Redis的配置与使用
  • 文章目录
  • 站点概览
Bennett

Bennett

60 日志
28 分类
74 标签
RSS
Github E-mail Gitee QQ
Creative Commons
Links
  • MacWk
  • 知了
0%
© 2020 — 2023 hibennett.cn版权所有
由 Halo 强力驱动
|
主题 - NexT.Pisces v5.1.4

浙公网安备 33010802011246号

    |    浙ICP备2020040857号-1