1. 什么是循环依赖
循环依赖就是循环引用,也就是两个或者两个以上的Bean相互持有对方,行程闭环。比如:对象A依赖对象B,对象B又依赖A。如下图:
2.Spring中循环依赖代码演示
@Service
public class ProductService {
@Autowired
private OrderService orderService;
}
@Service
public class OrderService {
@Autowired
private ProductService productService;
}
@ComponentScan("org.springframework.examples.xhyl")
public class XhylAppliactionTests{
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(XhylAppliactionTests.class);
}
}
3.Spring中循环依赖的解决方案
Spring 中解决循环依赖问题,只能够保证解决单例模式下的Bean创建的属性注入和Set注入时的循环依赖问题。原型或者构造器注入是无法解决的,执行过程中会直接异常。
主要是通过对象提前暴露和Spring中设计的经典三级缓存方式来解决的。
我们看下源码中的三级缓存,很简单,就是三个map:
/** Cache of singleton objects: bean name --> bean instance 真正完整的Bean对象*/
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(256);
/** Cache of singleton factories: bean name --> ObjectFactory bean的延时创建 */
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<String, ObjectFactory<?>>(16);
/** Cache of early singleton objects: bean name --> bean instance 主要是用来提前暴露对象 */
private final Map<String, Object> earlySingletonObjects = new HashMap<String, Object>(16);
三级缓存Map解读:
singletonFactories : 单例对象工厂的cache,Bean的延时加载
earlySingletonObjects :提前暴光的单例对象的Cache(不完整)
singletonObjects:单例对象的cache,完成的Bean对象