Spring Bean加载流程分析(通过 XML 方式加载)(13)

以上的代码做了如下几件事情
1.根据 beanName 去单例的缓存中检查是否已经存在该 Bean 对象
那么检查是如何进行的呢?通过 getSingleton 可以一窥究竟 。
// 传入的 allowEarlyReference 为 true/** Cache of singleton objects: bean name to bean instance. */private final Map singletonObjects = new ConcurrentHashMap<>(256);@Nullableprotected Object getSingleton(String beanName, boolean allowEarlyReference) {Object singletonObject = this.singletonObjects.get(beanName);if (singletonObject == nullif (singletonObject == nullif (singletonFactory != null) {singletonObject = singletonFactory.getObject();this.earlySingletonObjects.put(beanName, singletonObject);this.singletonFactories.remove(beanName);}}}}return singletonObject;}复制代码可以看到从当前的 singletonObjects 对象中获取了 singletonObject 对象 , singletonObject 对象为一个 ConcurrentHashMap 对象 , 用来缓存 SpringIOC 容器初始化过后的 bean 。 并且只会缓存 scope 属性为单例的 bean , prototype 属性的 bean 不会缓存 。
如果缓存对象为空 , 并且当前对象处于正在创建的时候 , 就开始处理循环引用的问题 。 如果当前缓存的对象不为空 , 那么直接返回当前缓存的 singletonObject;
这里涉及到一个循环引用的问题 , 后面单开文章来进行讲解 。 此处我们主要分析 bean 的创建过程 。
显然我们这里是第一次获取 , 所以 singletonObjects 这个 ConcurrentHashMap 中并不存在该对象的实例 。
【Spring Bean加载流程分析(通过 XML 方式加载)】作者:不荒链接:来源:掘金著作权归作者所有 。 商业转载请联系作者获得授权 , 非商业转载请注明出处 。


推荐阅读