[Sping] Spring 源码分析之从单例缓存中获取单例Bean

单例 bean 的加载是首先要从单例缓存中获取,如果缓存中没有才会进行bean 的加载。这里我们分析从缓存获取bean的过程。
AbstractBeanFactory 当中的doGetBean() 方法中首先从单例bean缓存中获取bean

Object sharedInstance = getSingleton(beanName);

继续跟踪源码到了 DefaultSingletonBeanRegistry 中的 getSingleton() 方法,如下:

/**
	 * Return the (raw) singleton object registered under the given name.
	 * <p>Checks already instantiated singletons and also allows for an early
	 * reference to a currently created singleton (resolving a circular reference).
	 * @param beanName the name of the bean to look for
	 * @param allowEarlyReference whether early references should be created or not
	 * @return the registered singleton object, or {@code null} if none found
	 */
	protected Object getSingleton(String beanName, boolean allowEarlyReference) {
	    // 从单例缓存中获取bean
		Object singletonObject = this.singletonObjects.get(beanName);
		// 单例缓存中没有该bean且 当前bean 正在创建
		if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
		    // 加锁
			synchronized (this.singletonObjects) {
			    // 从早期单例bean缓存中获取bean
				singletonObject = this.earlySingletonObjects.get(beanName);
				// 如果bean为空且允许早期创建
				if (singletonObject == null && allowEarlyReference) {
					// 获取该bean的beanFactory
					ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
					
					if (singletonFactory != null) {
					     // 使用  singletonFactory  创建bean
						singletonObject = singletonFactory.getObject();
						// 添加到 earlySingletonObjects 缓存中
						this.earlySingletonObjects.put(beanName, singletonObject);       // 添加到 singletonFactories 缓存中
						this.singletonFactories.remove(beanName);
					}
				}
			}
		}
		return (singletonObject != NULL_OBJECT ? singletonObject : null);
	}
  1. singletonObjects 获取
  2. 如果 singletonObjects 没有则从earlySingletonObjects 中获取
  3. 如果earlySingletonObjects 中没有,则使用bean的 beanFactory 也就是从singletonFactories 获取 singletonFactory ,使用 singletonFactory 获取到 singletonObject
  4. 将 singletonObject 添加到 earlySingletonObjects 缓存中,从 singletonFactories 移除bea对应的beanFactory
  5. return singletonObject

版权声明:本文为u013493841原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。