spring bean 循环依赖问题,在本地环境可以,测试环境报循环依赖问题
spring 在某些情况下是存在这样的问题:
https://github.com/spring-projects/spring-framework/issues/18879
https://github.com/spring-projects/spring-framework/issues/24325
https://stackoverflow.com/questions/29347723/why-does-spring-get-circular-dependency-issues-on-one-machine-and-not-another
解决办法:
1. 去循环依赖
2. @Lazy
3. InitializingBean 时,从 context 中获取
4. @PostConstruct 去设置 bean 依赖
https://www.baeldung.com/circular-dependencies-in-spring
为什么在本地可以,上了测试环境就不行,或者上了生产环境就不行了?
答:根源在于在不同的操作系统或者环境下, bean 的加载顺序是不固定的。bean 加载顺序变化之后,就可能会导致循环依赖报错问题产生!因为,顺序变化之后,循环依赖的主体变了!
bean 加载时,会先将所有的 BeanDefinition 扫描出来,扫描出来的顺序基本上就决定了 bean 的加载顺序。
扫描 BeanDefiniton 的方法是 ClassPathScanningCandidateComponentProvider#scanCandidateComponents(),这个方法在不同的环境下扫描出类的顺序是不固定的。
它的底层走的是 java.lang.ClassLoader#getResources() ,这个方法没有承诺获取到资源文件的顺序!
1 // PathMatchingResourcePatternResolver#doFindAllClassPathResources 2 protected Set<Resource> doFindAllClassPathResources(String path) throws IOException { 3 Set<Resource> result = new LinkedHashSet<>(16); 4 ClassLoader cl = getClassLoader(); 5 Enumeration<URL> resourceUrls = (cl != null ? cl.getResources(path) : ClassLoader.getSystemResources(path)); 6 while (resourceUrls.hasMoreElements()) { 7 URL url = resourceUrls.nextElement(); 8 result.add(convertClassLoaderURL(url)); 9 } 10 if (!StringUtils.hasLength(path)) { 11 // The above result is likely to be incomplete, i.e. only containing file system references. 12 // We need to have pointers to each of the jar files on the classpath as well... 13 addAllClassLoaderJarRoots(cl, result); 14 } 15 return result; 16 }
如果不清楚循环依赖的主体是什么意思,可以参考博主的另外一篇文章:https://blog.csdn.net/wang489687009/article/details/122284171#_61
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
· 零经验选手,Compose 一天开发一款小游戏!