循环依赖
两个或两个以上对象互相依赖对方,形成一个依赖环,例如A对象依赖B对象,B对象依赖A对象。
当创建相互依赖的对象时,会形成死循环,例如下图无缓存中的情况。而Spring通过增加缓存,将未完全创建好的A提前暴露在缓存中,当相互依赖的对象B对属性A赋值时,可以直接从缓存中获取A,而不需要再创建A,例如下图有缓存中的情况。
Spring的三级缓存
Spring的三级缓存分别为:
-
singletonObject:一级缓存,缓存中的bean是已经创建完成的,该bean经历过实例化->属性填充->初始化以及各种的后置处理。因此,一旦需要获取bean时,会优先寻找一级缓存
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) { Assert.notNull(beanName, "Bean name must not be null"); synchronized (this.singletonObjects) { // ... Object singletonObject = this.singletonObjects.get(beanName); if (singletonObject == null) { // bean创建前操作,标记当前bean正在创建 beforeSingletonCreation(beanName); boolean newSingleton = false; try { // 创建bean singletonObject = singletonFactory.getObject(); newSingleton = true; } catch (Exception ex) { // ... } finally { if (recordSuppressedExceptions) { this.suppressedExceptions = null; } // bean创建后操作,删除当前bean正在创建 afterSingletonCreation(beanName); } if (newSingleton) { // 存入一级缓存 addSingleton(beanName, singletonObject); } } return singletonObject; } } // 在bean创建完成之后,将bean加入到一级缓存中 protected void addSingleton(String beanName, Object singletonObject) { synchronized (this.singletonObjects) { // 添加一级缓存 this.singletonObjects.put(beanName, singletonObject); this.singletonFactories.remove(beanName); this.earlySingletonObjects.remove(beanName); this.registeredSingletons.add(beanName); } } 复制代码
-
earlySingletonObjects:二级缓存,该缓存跟一级缓存的区别在于,该缓存所获取到的bean是提前曝光出来的,是还没创建完成的。也就是说获取到的bean只能确保已经进行了实例化,但是属性填充跟初始化还没有做完,因此该bean还没创建完成,时半成品,仅仅能作为指针提前曝光ÿ