Spring Bean 创建过程源码分析

getSingleton()

DefaultSingletonBeanRegistry类中184行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) {
		Object singletonObject = this.singletonObjects.get(beanName);
		if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
			synchronized (this.singletonObjects) {
				singletonObject = this.earlySingletonObjects.get(beanName);
				if (singletonObject == null && allowEarlyReference) {
					ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
					if (singletonFactory != null) {
						singletonObject = singletonFactory.getObject();
						this.earlySingletonObjects.put(beanName, singletonObject);
						this.singletonFactories.remove(beanName);
					}
				}
			}
		}
		return (singletonObject != NULL_OBJECT ? singletonObject : null);
	}

getSingleton()方法作用是去查找单例的bean有没有注入到spring容器中,分为三个判断步骤

  1. 首先判断singletonObjects中有没有对应的bean,singletonObjects存储的是已经创建好的单例bean。
  2. 如果第一步没找到,那么去earlySingletonObjects中查找,earlySingletonObjects存储的是经过实例化的bean对象,还没有进行属性赋值和初始化。
  3. 如果第二步还是没有找到,那么去singletonFactories中进行查找,singletonFactories存储的是经过实例化并且被AOP包装后的代理类,意在解决循环依赖时AOP时产生的问题

If there is AOP, a depends on B, and B depends on A. After instantiation, a exposes it, starts injecting attributes, finds references to B, B starts instantiation, uses the object exposed by a, encapsulates it into a proxy object after initialization, and a injects B after the proxy and acts as a proxy. Then B in agent a is B after the proxy, but a in B after the proxy is a useless proxy.

请添加图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值