Spring循环依赖

基本概念:

  两个或两个以上的类相互引用、互相依赖;

Java使用构造器不能解决循环依赖问题;

Java可以使用setter解决循环依赖问题;

 

Spring中:

 

内部通过三级缓存来解决循环依赖问题(DefaultSingletonBeanRegistry)

只有单例的 bean 会通过三级缓存提前暴露来解决循环依赖问题,而非单例的 bean 每次从容器获取的都是一个新对象,都会重新创建,所以非单例的 bean是没有缓存的,不会放到三级缓存中;

一级缓存(也叫单例池)singletonObjects:存放已经经历了完整生命周期的 Bean对象;

二级缓存 earlySingletonObjects:存放早期暴露出来的 Bean对象,Bean的生命周期未结束(属性还未填充完整的);

三级缓存 Map<String, ObjectFactory<?>> singletonFactories:存放可以生成 Bean的工厂;

 

 

spring循环依赖总结:

复制代码
    @Nullable
    protected Object getSingleton(String beanName, boolean allowEarlyReference) {
        Object singletonObject = this.singletonObjects.get(beanName);
        if (singletonObject == null && this.isSingletonCurrentlyInCreation(beanName)) {
            //一级缓存没有的话,就去二级缓存中找
            singletonObject = this.earlySingletonObjects.get(beanName);
            if (singletonObject == null && allowEarlyReference) {
                synchronized (this.singletonObjects) {
                    singletonObject = this.singletonObjects.get(beanName);
                    if (singletonObject == null) {
                        singletonObject = this.earlySingletonObjects.get(beanName);
                        if (singletonObject == null) {
                            //二级缓存没有的话就去三级缓存中找
                            ObjectFactory<?> singletonFactory = (ObjectFactory) this.singletonFactories.get(beanName);
                            if (singletonFactory != null) {
                                //三级缓存中存在的话
                                singletonObject = singletonFactory.getObject();
                                //就把它移动到二级缓存中
                                this.earlySingletonObjects.put(beanName, singletonObject);
                                //三级缓存中的移除
                                this.singletonFactories.remove(beanName);
                            }
                        }
                    }
                }
            }
        }
        return singletonObject;
    }
复制代码

 

posted @   DHaiLin  阅读(73)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示