Spring 5 AbstractBeanFactory -- getObjectFromFactoryBean 源码解析

相关源码注释

ApplicationContext

Spring 5 DefaultResourceLoader 源码注释
Spring 5 AbstractApplicationContext 源码注释

BeanFactory

Spring 5 SimpleAliasRegistry 源码注释
Spring 5 DefaultSingletonBeanRegistry 源码注释
Spring 5 FactoryBeanRegistrySupport 源码注释
Spring 5 AbstractBeanFactory 源码注释
Spring 5 AbstractAutowireCapableBeanFactory 源码注释
Spring 5 DefaultLisbaleBeanFactory 源码注释

AbstractBeanFactory 继承了 FactoryBeanRegistrySupport ,引用其实现方法 getObjectFromFactoryBean。

FactoryBeanRegistrySupport # getObjectFromFactoryBean

从BeanFactory对象中获取管理的对象.可根据shouldPostProcess对其对象进行该工厂的后置处理:

  1. 如果factory管理的对象是单例 且 beanName已经在该BeanFactory的单例对象的高速缓存Map集合【DefaultListableBeanFactory.singletonObjects】中:
    1. 获取单例互斥体(一般使用singletonObjects)进行加锁,来保证线程安全:
    2. 获取beanName的Bean对象【变量 object】:
      1. 获取factory管理的对象实例并赋值给object
      2. 重新从factoryBeanObjectCache中获取beanName对应bean对象【变量 alreadyThere】
      3. 如果bean对象不为null,让object引用alreadyThere
      4. 否则:
        1. 如果要进行后处理【shouldPostProcess】:
          1. 如果beanName当前正在创建(在整个工厂内),直接返回object
          2. 创建单例之前的回调【beforeSingletonCreation(String)】
          3. 对从FactoryBean获得的给定对象进行后处理.将处理后的对象重新赋值给object
          4. 捕捉所有在进行后处理的抛出的异常,抛出Bean创建异常
          5. 【finally】:创建单例后的回调【afterSingletonCreation(String)】
        2. beanName已经在该BeanFactory的单例对象的高速缓存Map集合【DefaultListableBeanFactory.singletonObjects】中 将beanName以及object添加到factoryBeanObjectCache中
      5. 返回factory管理的对象实例(该对象已经过工厂的后处理)【object】
  2. 否则:
    1. 获取factory管理的对象实例【变量 object】
    2. 如果要进行后处理【shouldPostProcess】:
      1. 对从FactoryBean获得的给定对象进行后处理并赋值给object
      2. 捕捉所有在进行后处理的抛出的异常,抛出Bean创建异常:FactoryBean的单例对象的后处理失败
    3. 返回factory管理的对象实例(该对象已经过工厂的后处理)【object】
/**
	 * Obtain an object to expose from the given FactoryBean.
	 * <p>获取一个对象以从给定的FactoryBean中公开</p>
	 * @param factory the FactoryBean instance -- FactoryBean实例
	 * @param beanName the name of the bean -- bean名
	 * @param shouldPostProcess whether the bean is subject to post-processing -- Bean是否要进行后处理
	 * @return the object obtained from the FactoryBean -- 从FactoryBean获得的对象
	 * @throws BeanCreationException if FactoryBean object creation failed
	 * 									-- 如果FactoryBean对象创建失败
	 * @see org.springframework.beans.factory.FactoryBean#getObject()
	 */
	protected Object getObjectFromFactoryBean(FactoryBean<?> factory, String beanName, boolean shouldPostProcess) {
    
    
		//如果factory管理的对象是单例 且 beanName已经在该BeanFactory的单例对象的高速缓存Map集合【DefaultListableBeanFactory.singletonObjects】中
		if (factory.isSingleton() && containsSingleton(beanName)) {
    
    
			//获取单例互斥体(一般使用singletonObjects)进行加锁,来保证线程安全
			synchronized (getSingletonMutex()) {
    
    
				//获取beanName的Bean对象
				Object object = this.factoryBeanObjectCache.get(beanName);
				//如果object为null
				if (object == null) {
    
    
					//获取factory管理的对象实例并赋值给object
					object = doGetObjectFromFactoryBean(factory, beanName);
					// Only post-process and store if not put there already during getObject() call above
					// (e.g. because of circular reference processing triggered by custom getBean calls)
					// 仅在上面的getObject()调用期间进行后处理和存储(如果尚未放置)
					// (例如,由于自定义getBean调用触发的循环引用处理)
					//重新从factoryBeanObjectCache中获取beanName对应bean对象
					Object alreadyThere = this.factoryBeanObjectCache.get(beanName);
					//如果bean对象不为null
					if (alreadyThere != null) {
    
    
						//让object引用alreadyThere
						object = alreadyThere;
					}
					else {
    
    
						//如果要进行后处理
						if (shouldPostProcess) {
    
    
							//如果beanName当前正在创建(在整个工厂内)
							if (isSingletonCurrentlyInCreation(beanName)) {
    
    
								// Temporarily return non-post-processed object, not storing it yet..
								// 暂时返回未处理的对象,尚未存储
								//直接返回object
								return object;
							}
							//创建单例之前的回调
							beforeSingletonCreation(beanName);
							try {
    
    
								//对从FactoryBean获得的给定对象进行后处理.
								object = postProcessObjectFromFactoryBean(object, beanName);
							}
							//捕捉所有在进行后处理的抛出的异常
							catch (Throwable ex) {
    
    
								//抛出Bean创建异常:FactoryBean的单例对象的后处理失败
								throw new BeanCreationException(beanName,
										"Post-processing of FactoryBean's singleton object failed", ex);
							}
							finally {
    
    
								//创建单例后的回调
								afterSingletonCreation(beanName);
							}
						}
						//beanName已经在该BeanFactory的单例对象的高速缓存Map集合【DefaultListableBeanFactory.singletonObjects】中
						if (containsSingleton(beanName)) {
    
    
							//将beanName以及object添加到factoryBeanObjectCache中
							this.factoryBeanObjectCache.put(beanName, object);
						}
					}
				}
				//返回factory管理的对象实例(该对象已经过工厂的后处理)
				return object;
			}
		}
		else {
    
    
//			//获取factory管理的对象实例
			Object object = doGetObjectFromFactoryBean(factory, beanName);
			//如果要进行后处理
			if (shouldPostProcess) {
    
    
				try {
    
    
					//对从FactoryBean获得的给定对象进行后处理
					object = postProcessObjectFromFactoryBean(object, beanName);
				}
				//捕捉所有在进行后处理的抛出的异常
				catch (Throwable ex) {
    
    
					//抛出Bean创建异常:FactoryBean的单例对象的后处理失败
					throw new BeanCreationException(beanName, "Post-processing of FactoryBean's object failed", ex);
				}
			}
			//返回factory管理的对象实例(该对象已经过工厂的后处理)
			return object;
		}
	}

containsSingleton(beanName)

判断一下beanName是否在该BeanFactory的单例对象的高速缓存Map集合。
containsSingleton(beanName) 由 DefaultSingletonBeanRegistry 实现

	/**
	 * Cache of singleton objects: bean name to bean instance.
	 * <p>单例对象的高速缓存:beam名称-bean实例,所有bean对象最终都会放到对象中</p>
	 * */
	private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);

	/**
	 * <p>只是判断一下beanName是否在该BeanFactory的单例对象的高速缓存Map集合【{@link DefaultListableBeanFactory#singletonObjects}】中</p>
	 * @param beanName the name of the bean to look for -- 要查找的bean名
	 * @return
	 */
	@Override
	public boolean containsSingleton(String beanName) {
    
    
		return this.singletonObjects.containsKey(beanName);
	}

getSingletonMutex()

获取单例互斥体,一般使用 singletonObjects .
getSingletonMutex() 由 DefaultSingletonBeanRegistry 实现


/**
	 * Cache of singleton objects: bean name to bean instance.
	 * <p>单例对象的高速缓存:beam名称-bean实例,所有bean对象最终都会放到对象中</p>
	 * */
	private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
	
	/**
	 * 
	 * Exposes the singleton mutex to subclasses and external collaborators.
	 * <p>将单例互斥暴露给子类和外部协作者</p>
	 * <p>Subclasses should synchronize on the given Object if they perform
	 * any sort of extended singleton creation phase. In particular, subclasses
	 * should <i>not</i> have their own mutexes involved in singleton creation,
	 * to avoid the potential for deadlocks in lazy-init situations.
	 * <p>如果子类执行任何扩展的单例创建阶段,则它们应在给定Object上同步.特别是,子类不应
	 * 在单例创建中涉及其自己的互斥体,以避免在惰性初始化情况下出现死锁的可能性</p>
	 */
	@Override
	public final Object getSingletonMutex() {
    
    
		return this.singletonObjects;
	}

doGetObjectFromFactoryBean(factory, beanName)

获取factory管理的对象实例:

  1. 定义一个用于保存factory管理的对象实例的变量【变量 object】
  2. 如果有安全管理器:
    1. 获取访问控制的上下文对象【变量 acc】
    2. 以特权方式运行来获取factory管理的对象实例赋值给object
  3. 否则 获取factory管理的对象实例赋值给object
  4. 捕捉FactoryBean未初始化异常【变量 ex】,引用ex的异常描述,重新抛出 当前正在创建Bean异常
  5. 捕捉剩余的所有异常,重新抛出Bean创建异常:FactoryBean在对象创建时引发异常
  6. 如果object为null:
    1. 如果 beanName当前正在创建(在整个工厂内),抛出 当前正在创建Bean异常
    2. 让object引用一个新的NullBean实例
  7. 返回 factory管理的对象实例【object】
/**
	 * Obtain an object to expose from the given FactoryBean.
	 * <p>获取一个对象以从给定的FactoryBean中公开</p>
	 * @param factory the FactoryBean instance -- FactoryBean实例
	 * @param beanName the name of the bean -- bean名
	 * @return the object obtained from the FactoryBean -- 从FactoryBean获取对象
	 * @throws BeanCreationException if FactoryBean object creation failed
	 *   -- 如果FactoryBean对象创建失败
	 * @see org.springframework.beans.factory.FactoryBean#getObject()
	 */
	private Object doGetObjectFromFactoryBean(final FactoryBean<?> factory, final String beanName)
			throws BeanCreationException {
    
    
		//定义一个用于保存factory管理的对象实例的变量
		Object object;
		try {
    
    
			//如果有安全管理器
			if (System.getSecurityManager() != null) {
    
    
				//获取访问控制的上下文对象
				AccessControlContext acc = getAccessControlContext();
				try {
    
    
					//以特权方式运行来获取factory管理的对象实例赋值给object
					object = AccessController.doPrivileged((PrivilegedExceptionAction<Object>) factory::getObject, acc);
				}
				catch (PrivilegedActionException pae) {
    
    
					throw pae.getException();
				}
			}
			else {
    
    
				//获取factory管理的对象实例赋值给object
				object = factory.getObject();
			}
		}
		//捕捉FactoryBean未初始化异常
		catch (FactoryBeanNotInitializedException ex) {
    
    
			//引用ex的异常描述,重新抛出当前正在创建Bean异常
			throw new BeanCurrentlyInCreationException(beanName, ex.toString());
		}
		//捕捉剩余的所有异常
		catch (Throwable ex) {
    
    
			//重新抛出Bean创建异常:FactoryBean在对象创建时引发异常
			throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex);
		}

		// Do not accept a null value for a FactoryBean that's not fully
		// initialized yet: Many FactoryBeans just return null then.
		// 不接受尚未完全初始化的FactoryBean的null值:然后,许多FactoryBeans仅返回null
		//如果object为null
		if (object == null) {
    
    
			//如果 beanName当前正在创建(在整个工厂内)
			if (isSingletonCurrentlyInCreation(beanName)) {
    
    
				//抛出 当前正在创建Bean异常:当前正在创建的FactoryBean从getObject返回null
				throw new BeanCurrentlyInCreationException(
						beanName, "FactoryBean which is currently in creation returned null from getObject");
			}
			//让object引用一个新的NullBean实例
			object = new NullBean();
		}
		//返回 factory管理的对象实例【object】
		return object;
	}

isSingletonCurrentlyInCreation(beanName)

返回指定的单例bean当前是否正在创建(在整个工厂内).由 DefaultSingletonBeanRegistry 实现

/**
	 * Names of beans that are currently in creation.
	 * <p>当前正在创建的bean名称</p>
	 * <p>Collections.newSetFromMap(Map):Collections提供了一种保证元素唯一性的Map实现,
	 * 就是用一个Set来表示Map,它持有这个Map的引用,并且保持Map的顺序、并发和性能特征。</p>
	 *  */
	private final Set<String> singletonsCurrentlyInCreation =
			Collections.newSetFromMap(new ConcurrentHashMap<>(16));
			
/**
	 * Return whether the specified singleton bean is currently in creation
	 * (within the entire factory).
	 * <p>返回指定的单例bean当前是否正在创建(在整个工厂内)</p>
	 * @param beanName the name of the bean - bean名
	 */
	public boolean isSingletonCurrentlyInCreation(String beanName) {
    
    
		//从 当前正在创建的bean名称 set集合中判断beanName是否在集合中
		return this.singletonsCurrentlyInCreation.contains(beanName);
	}

beforeSingletonCreation(beanName);

创建单例之前的回调:
如果 当前在创建检查中的排除bean名列表【inCreationCheckExclusions】中不包含该beanName 且 将beanName添加到 当前正在创建的bean名称列表【singletonsCurrentlyInCreation】后,出现beanName已经在当前正在创建的bean名称列表中添加过

/**
	 * Callback before singleton creation.
	 * <p>创建单例之前的回调</p>
	 * <p>The default implementation register the singleton as currently in creation.
	 * <p>默认实现将单例注册为当前正在创建中</p>
	 * @param beanName the name of the singleton about to be created
	 * @see #isSingletonCurrentlyInCreation
	 */
	protected void beforeSingletonCreation(String beanName) {
    
    
		//如果 当前在创建检查中的排除bean名列表中不包含该beanName 且 将beanName添加到 当前正在创建的bean名称列表后,出现
		// beanName已经在当前正在创建的bean名称列表中添加过
		if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.add(beanName)) {
    
    
			//抛出 当前正在创建的Bean异常
			throw new BeanCurrentlyInCreationException(beanName);
		}
	}

postProcessObjectFromFactoryBean(object, beanName);

FactoryBeanRegistrySupport # postProcessObjectFromFactoryBean 是钩子方法

   /**
    * Post-process the given object that has been obtained from the FactoryBean.
    * The resulting object will get exposed for bean references.
    * <p>对从FactoryBean获得的给定对象进行后处理.生成的对象将暴露给Bean引用</p>
    * <p>The default implementation simply returns the given object as-is.
    * Subclasses may override this, for example, to apply post-processors.
    * <p>默认实现只是按原样返回给定的对象.子类可以覆盖它,例如以应用后处理器</p>
    * @param object the object obtained from the FactoryBean.
    *                -- 从FactoryBean获得的对象
    * @param beanName the name of the bean -- bean名
    * @return the object to expose -- 暴露的对象
    * @throws org.springframework.beans.BeansException if any post-processing failed
    */
   protected Object postProcessObjectFromFactoryBean(Object object, String beanName) throws BeansException {
    
    
   	return object;
   }

AbstractAutowireCapableBeanFactory 重写了该方法:

	/**
	 * Applies the {@code postProcessAfterInitialization} callback of all
	 * registered BeanPostProcessors, giving them a chance to post-process the
	 * object obtained from FactoryBeans (for example, to auto-proxy them).
	 * <p>应用所有已注册BeanPostProcessor的postProcessAfterInitalization回调,使它
	 * 们有机会对FactoryBeans获得的对象进行后处理(例如,自动代理它们)</p>
	 * @see #applyBeanPostProcessorsAfterInitialization
	 */
	@Override
	protected Object postProcessObjectFromFactoryBean(Object object, String beanName) {
    
    
		//初始化后的后处理
		return applyBeanPostProcessorsAfterInitialization(object, beanName);
	}

applyBeanPostProcessorsAfterInitialization(object, beanName)

对 existingBean 进行初始化后的后处理::

  1. 初始化结果对象为result,默认引用existingBean
  2. 遍历该工厂创建的bean的BeanPostProcessors列表:
    1. 回调BeanPostProcessor#postProcessAfterInitialization来对result进行包装【变量 current】
    2. 如果current为null,直接返回result,中断其后续的BeanPostProcessor处理
    3. 让result引用current,使其经过所有BeanPostProcess对象的后置处理的层层包装
  3. 返回经过所有BeanPostProcess对象的后置处理的层层包装后的result
/**
	 * 对 existingBean 进行初始化后的后处理:
	 * @param existingBean the existing bean instance -- 现有的bean实例
	 * @param beanName the name of the bean, to be passed to it if necessary
	 * (only passed to {@link BeanPostProcessor BeanPostProcessors};
	 * can follow the {@link #ORIGINAL_INSTANCE_SUFFIX} convention in order to
	 * enforce the given instance to be returned, i.e. no proxies etc)
	 * Bean名称,必要时将传递给它(仅传递给BeanPostProcessor;可以遵循ORIGINAL_INSTANCE_SUFFIX
	 * 约定以强制返回给定的实例,即没有代理等)
	 * @return
	 * @throws BeansException
	 */
	@Override
	public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
			throws BeansException {
    
    
		//初始化结果对象为result,默认引用existingBean
		Object result = existingBean;
		//遍历该工厂创建的bean的BeanPostProcessors列表
		for (BeanPostProcessor processor : getBeanPostProcessors()) {
    
    
			//回调BeanPostProcessor#postProcessAfterInitialization来对现有的bean实例进行包装
			Object current = processor.postProcessAfterInitialization(result, beanName);
			//一般processor对不感兴趣的bean会回调直接返回result,使其能继续回调后续的BeanPostProcessor;
			// 但有些processor会返回null来中断其后续的BeanPostProcessor
			//如果current为null
			if (current == null) {
    
    
				//直接返回result,中断其后续的BeanPostProcessor处理
				return result;
			}
			//让result引用processor的返回结果,使其经过所有BeanPostProcess对象的后置处理的层层包装
			result = current;
		}
		//返回经过所有BeanPostProcess对象的后置处理的层层包装后的result
		return result;
	}

afterSingletonCreation(beanName)

afterSingletonCreation(beanName) 由 DefaultSingletonBeanRegistry 实现
创建单例后的回调
如果 当前在创建检查中的排除bean名列表中不包含该beanName 且 将beanName从 当前正在创建的bean名称列表 异常后,出现 beanName已经没在当前正在创建的bean名称列表中出现过

/**
	 * Callback after singleton creation.
	 * <p>创建单例后的回调</p>
	 * <p>The default implementation marks the singleton as not in creation anymore.
	 * <p>默认实现将单例标记为不在创建中</p>
	 * @param beanName the name of the singleton that has been created -- 已创建的单例的名称
	 * @see #isSingletonCurrentlyInCreation
	 */
	protected void afterSingletonCreation(String beanName) {
    
    
		//如果 当前在创建检查中的排除bean名列表中不包含该beanName 且 将beanName从 当前正在创建的bean名称列表 异常后,出现
		// beanName已经没在当前正在创建的bean名称列表中出现过
		if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.remove(beanName)) {
    
    
			//抛出非法状态异常:单例'beanName'不是当前正在创建的
			throw new IllegalStateException("Singleton '" + beanName + "' isn't currently in creation");
		}
	}

猜你喜欢

转载自blog.csdn.net/qq_30321211/article/details/108337265