spring 循环依赖是三个map缓存问题

	/**
	 * 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
	 */
	@Nullable
	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;
	}

spring 源码中的3个缓存map

	/** Cache of singleton objects: bean name to bean instance. */
	/** singletonObjects  一级缓存,可以理解为spring单利池 存放完整的bean*/
	
	private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);

	/** Cache of singleton factories: bean name to ObjectFactory. */
	/** 这个二级缓存 是一个bean工厂,可以生产bean(循环依赖aop--通过cglib代理产生一个新的类,问题等可以在这里实现),
	如果二级缓存直接是一个bean 的话,很多需要对bean 的加工都不能实现,这里对aop的实现是通过一个后置处理器AnnotationAwareAspectJAutoProxyCreator */
	private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);

	/** Cache of early singleton objects: bean name to bean instance. */
	
	/** 三级缓存spring 为什么要三级缓存呢,
	this.earlySingletonObjects.put(beanName, singletonObject);
	this.singletonFactories.remove(beanName);
	从二级缓存singletonFactories remove,然后放入三级,因为有多个相同的依赖注入的话,
	防止singletonFactories 的重复创建,可以直接在earlySingletonObjects 中获取,提高性能。就好比你每次看病找老中医看了一个药方子,
	以后有这个病了就看药方子就行了,不用再重复去医院排队缴费,找老中医说你的症状,直接拿着药方子去买药吃就行了 */

	private final Map<String, Object> earlySingletonObjects = new HashMap<>(16);
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值