• Spring IoC源码:getBean 详解


    Spring源码系列:

    Spring IOC源码:简单易懂的Spring IOC 思路介绍
    Spring IOC源码:核心流程介绍
    Spring IOC源码:ApplicationContext刷新前准备工作
    Spring IOC源码:obtainFreshBeanFactory 详解(上)
    Spring IOC源码:obtainFreshBeanFactory 详解(中)
    Spring IOC源码:obtainFreshBeanFactory 详解(下)
    Spring IOC源码:<context:component-scan>源码详解
    Spring IOC源码:invokeBeanFactoryPostProcessors 后置处理器详解
    Spring IOC源码:registerBeanPostProcessors 详解
    Spring IOC源码:实例化前的准备工作
    Spring IOC源码:finishBeanFactoryInitialization详解
    Spring IoC源码:getBean 详解
    Spring IoC源码:createBean( 上)
    Spring IoC源码:createBean( 中)
    Spring IoC源码:createBean( 下)
    Spring IoC源码:finishRefresh 完成刷新详解

    前言

    这篇文章继续讲解bean的实例化过程,也是实例化的一个重要入口getBean(beanName)方法。传入beanName后,会尝试从一级缓存中获取完整的Bean实例,获取不到则进行创建过程。

    正文

    续上篇文章的preInstantiateSingletons方法,进入getBean(beanName)方法,其参数为bean名称。

    	@Override
    	public Object getBean(String name) throws BeansException {
    		return doGetBean(name, null, null, false);
    	}
    
    • 1
    • 2
    • 3
    • 4
    protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
    			@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
    		//去除&符号,尝试从别名缓存中获取beanName
    		final String beanName = transformedBeanName(name);
    		Object bean;
    
    		// Eagerly check singleton cache for manually registered singletons.
    		//从三级缓存中获取对象
    		Object sharedInstance = getSingleton(beanName);
    		if (sharedInstance != null && args == null) {
    			if (logger.isTraceEnabled()) {
    				if (isSingletonCurrentlyInCreation(beanName)) {
    					logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
    							"' that is not fully initialized yet - a consequence of a circular reference");
    				}
    				else {
    					logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
    				}
    			}
    			//1、将sharedInstance实例传入,主要是对工厂bean的处理,普通的bean会返回传入的对象
    			bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
    		}
    
    		else {
    			// Fail if we're already creating this bean instance:
    			// We're assumably within a circular reference.
    			//如果是原型模式,避免出现循环依赖的情况。A中有B,B中有A。在创建A后的,属性注入创建B,B属性注入会创建A,由于是原型模式所以会走这段逻辑
    			if (isPrototypeCurrentlyInCreation(beanName)) {
    				throw new BeanCurrentlyInCreationException(beanName);
    			}
    
    			// Check if bean definition exists in this factory.
    			//如果存在父工厂,且当前工厂中不存在该bean的定义信息
    			BeanFactory parentBeanFactory = getParentBeanFactory();
    			if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
    				// Not found -> check parent.
    				String nameToLookup = originalBeanName(name);
    				//从父工厂中进行查找
    				if (parentBeanFactory instanceof AbstractBeanFactory) {
    					return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
    							nameToLookup, requiredType, args, typeCheckOnly);
    				}
    				else if (args != null) {
    					// Delegation to parent with explicit args.
    					return (T) parentBeanFactory.getBean(nameToLookup, args);
    				}
    				else if (requiredType != null) {
    					// No args -> delegate to standard getBean method.
    					return parentBeanFactory.getBean(nameToLookup, requiredType);
    				}
    				else {
    					return (T) parentBeanFactory.getBean(nameToLookup);
    				}
    			}
    
    			if (!typeCheckOnly) {
    			//2、标志为创建中
    				markBeanAsCreated(beanName);
    			}
    
    			try {
    				//获取合并的Bean定义信息,typeCheckOnly检查时会删除了定义信息,这里重新创建
    				final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
    				//检查RootBeanDefinition 的Abstract属性是否为true,如果是则抛异常
    				checkMergedBeanDefinition(mbd, beanName, args);
    
    				// Guarantee initialization of beans that the current bean depends on.
    				//获取依赖类名称,实例化自己前先实例化依赖
    				String[] dependsOn = mbd.getDependsOn();
    				if (dependsOn != null) {
    					for (String dep : dependsOn) {
    					  //3、检查dep是否依赖于beanName,即检查是否存在循环依赖
    						if (isDependent(beanName, dep)) {
    							throw new BeanCreationException(mbd.getResourceDescription(), beanName,
    									"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
    						}
    						//4、注册绑定依赖关系到缓存中
    						registerDependentBean(dep, beanName);
    						try {
    							//获取依赖,如果未创建则创建,这一步的目的就是为了先实例化其依赖
    							getBean(dep);
    						}
    						catch (NoSuchBeanDefinitionException ex) {
    							throw new BeanCreationException(mbd.getResourceDescription(), beanName,
    									"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
    						}
    					}
    				}
    
    				// Create bean instance.
    				//如果是单例
    				if (mbd.isSingleton()) {
    					//5、创建实例,其参数为beanName,以及类型为ObjectFactory的匿名内部类
    					sharedInstance = getSingleton(beanName, () -> {
    						try {
    							//创建Bean
    							return createBean(beanName, mbd, args);
    						}
    						catch (BeansException ex) {
    							// Explicitly remove instance from singleton cache: It might have been put there
    							// eagerly by the creation process, to allow for circular reference resolution.
    							// Also remove any beans that received a temporary reference to the bean.
    							destroySingleton(beanName);
    							throw ex;
    						}
    					});
    					//如果是工厂bean,返回对应的实例,普通bean则直接返回不做任何处理
    					bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
    				}
    				//如果是原型模式
    				else if (mbd.isPrototype()) {
    					// It's a prototype -> create a new instance.
    					Object prototypeInstance = null;
    					try {
    						//创建实例前的操作,将beanName保存到prototypesCurrentlyInCreation缓存中
    						beforePrototypeCreation(beanName);
    						//创建实例
    						prototypeInstance = createBean(beanName, mbd, args);
    					}
    					finally {
    						//从prototypesCurrentlyInCreation缓存中移除
    						afterPrototypeCreation(beanName);
    					}
    					//如果是工厂bean,返回对应的实例,普通bean则直接返回不做任何处理
    					bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
    				}
    
    				else {
    					//获取scopeName值,从Scope缓存中获取自定义的Scope 实现类
    					String scopeName = mbd.getScope();
    					final Scope scope = this.scopes.get(scopeName);
    					if (scope == null) {
    						throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
    					}
    					try {
    					//传入ObjectFactory类型的匿名内部类,通过调用其getObject方法创建bean
    						Object scopedInstance = scope.get(beanName, () -> {
    						//创建实例前的操作,将beanName保存到prototypesCurrentlyInCreation缓存中
    							beforePrototypeCreation(beanName);
    							try {
    								return createBean(beanName, mbd, args);
    							}
    							finally {
    							//从prototypesCurrentlyInCreation缓存中移除
    								afterPrototypeCreation(beanName);
    							}
    						});
    						//如果是工厂bean,返回对应的实例,普通bean则直接返回不做任何处理
    						bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
    					}
    					catch (IllegalStateException ex) {
    						throw new BeanCreationException(beanName,
    								"Scope '" + scopeName + "' is not active for the current thread; consider " +
    								"defining a scoped proxy for this bean if you intend to refer to it from a singleton",
    								ex);
    					}
    				}
    			}
    			catch (BeansException ex) {
    				cleanupAfterBeanCreationFailure(beanName);
    				throw ex;
    			}
    		}
    
    		// Check if required type matches the type of the actual bean instance.
    		//检查所需类型是否与实际的bean对象的类型匹配
    		if (requiredType != null && !requiredType.isInstance(bean)) {
    			try {
    			//尝试类型转换
    				T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
    				if (convertedBean == null) {
    					throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
    				}
    				return convertedBean;
    			}
    			catch (TypeMismatchException ex) {
    				if (logger.isTraceEnabled()) {
    					logger.trace("Failed to convert bean '" + name + "' to required type '" +
    							ClassUtils.getQualifiedName(requiredType) + "'", ex);
    				}
    				throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
    			}
    		}
    		//返回实例
    		return (T) bean;
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186

    1、getObjectForBeanInstance(sharedInstance, name, beanName, null),见方法1详解
    2、markBeanAsCreated(beanName),见方法5详解
    3、isDependent(beanName, dep),见方法6详解
    4、registerDependentBean(dep, beanName),见方法7详解
    5、getSingleton,见方法8详解

    方法1:getObjectForBeanInstance

    	protected Object getObjectForBeanInstance(
    			Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) {
    
    		// Don't let calling code try to dereference the factory if the bean isn't a factory.
    		//判断name是否带&符号
    		if (BeanFactoryUtils.isFactoryDereference(name)) {
    			if (beanInstance instanceof NullBean) {
    				return beanInstance;
    			}
    			//带了&符号前缀,但是不是FactoryBean类型的,抛异常
    			if (!(beanInstance instanceof FactoryBean)) {
    				throw new BeanIsNotAFactoryException(beanName, beanInstance.getClass());
    			}
    			if (mbd != null) {
    				mbd.isFactoryBean = true;
    			}
    			//直接返回,因为带了&符号且是FactoryBean类型的,证明是要FactoryBean本身
    			return beanInstance;
    		}
    
    		// Now we have the bean instance, which may be a normal bean or a FactoryBean.
    		// If it's a FactoryBean, we use it to create a bean instance, unless the
    		// caller actually wants a reference to the factory.
    		//如果不是FactoryBean,则直接返回
    		if (!(beanInstance instanceof FactoryBean)) {
    			return beanInstance;
    		}
    		//是FactoryBean类型的,但是不带&符号,代表要返回其工厂中真正的实例
    		Object object = null;
    		if (mbd != null) {
    			mbd.isFactoryBean = true;
    		}
    		else {
    			//尝试从工厂缓存中获取
    			object = getCachedObjectForFactoryBean(beanName);
    		}
    		if (object == null) {
    			// Return bean instance from factory.
    			//转为FactoryBean实例
    			FactoryBean<?> factory = (FactoryBean<?>) beanInstance;
    			// Caches object obtained from FactoryBean if it is a singleton.
    			//判断beanDefinition缓存中是否存在
    			if (mbd == null && containsBeanDefinition(beanName)) {
    				//创建新的定义信息
    				mbd = getMergedLocalBeanDefinition(beanName);
    			}
    			//mbd是否是合成的
    			boolean synthetic = (mbd != null && mbd.isSynthetic());
    			//创建实例
    			object = getObjectFromFactoryBean(factory, beanName, !synthetic);
    		}
    		return object;
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53

    getObjectFromFactoryBean(factory, beanName, !synthetic),见方法2详解

    方法2:getObjectFromFactoryBean

    protected Object getObjectFromFactoryBean(FactoryBean<?> factory, String beanName, boolean shouldPostProcess) {
    		//如果factory对象是单例的,并且存在一级缓存中
    		if (factory.isSingleton() && containsSingleton(beanName)) {
    			synchronized (getSingletonMutex()) {
    				//从缓存中获取工厂中真正的实例
    				Object object = this.factoryBeanObjectCache.get(beanName);
    				if (object == null) {
    					//调用工厂Bean的getObject方法返回实例
    					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)
    					Object alreadyThere = this.factoryBeanObjectCache.get(beanName);
    					//如果该beanName已经在缓存中存在,则将object替换成缓存中的
    					if (alreadyThere != null) {
    						object = alreadyThere;
    					}
    					else {
    						if (shouldPostProcess) {
    							//如果当前beanName正在创建中则返回
    							if (isSingletonCurrentlyInCreation(beanName)) {
    								// Temporarily return non-post-processed object, not storing it yet..
    								return object;
    							}
    							//将beanName添加到singletonsCurrentlyInCreation缓存中
    							beforeSingletonCreation(beanName);
    							try {
    							//对bean实例进行后置处理,执行所有已注册的BeanPostProcessor的postProcessAfterInitialization方法
    								object = postProcessObjectFromFactoryBean(object, beanName);
    							}
    							catch (Throwable ex) {
    								throw new BeanCreationException(beanName,
    										"Post-processing of FactoryBean's singleton object failed", ex);
    							}
    							finally {
    							//将beanName从inCreationCheckExclusions缓存中移除
    								afterSingletonCreation(beanName);
    							}
    						}
    						if (containsSingleton(beanName)) {
    						//将beanName和object放到factoryBeanObjectCache缓存中
    							this.factoryBeanObjectCache.put(beanName, object);
    						}
    					}
    				}
    				return object;
    			}
    		}
    		else {
    		//非单例,调用FactoryBean的getObject方法获取对象实例
    			Object object = doGetObjectFromFactoryBean(factory, beanName);
    			if (shouldPostProcess) {
    				try {
    				//对bean实例进行后置处理,执行所有已注册的BeanPostProcessor的postProcessAfterInitialization方法
    					object = postProcessObjectFromFactoryBean(object, beanName);
    				}
    				catch (Throwable ex) {
    					throw new BeanCreationException(beanName, "Post-processing of FactoryBean's object failed", ex);
    				}
    			}
    			return object;
    		}
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62

    整体的流程就是从缓存中获取工厂Bean真正的实例对象,获取不到则调用getObject方法获取,并判断是否调用执行BeanPostProcessor后置处理器的postProcessAfterInitialization方法,调用后置处理器前后会将Bean加入及移除singletonsCurrentlyInCreation缓存,其作用是标识其正在创建,避免后置处理器执行过程中获取该实例,获取不到进行创建,导致出现循环依赖问题。

    doGetObjectFromFactoryBean(factory, beanName),见方法3详解
    postProcessObjectFromFactoryBean(object, beanName),见方法4详解

    方法3:doGetObjectFromFactoryBean

    private Object doGetObjectFromFactoryBean(final FactoryBean<?> factory, final String beanName)
    			throws BeanCreationException {
    
    		Object object;
    		//调用FactoryBean的getObject方法获取bean对象实例
    		try {
    			if (System.getSecurityManager() != null) {
    				AccessControlContext acc = getAccessControlContext();
    				try {
    					object = AccessController.doPrivileged((PrivilegedExceptionAction<Object>) factory::getObject, acc);
    				}
    				catch (PrivilegedActionException pae) {
    					throw pae.getException();
    				}
    			}
    			else {
    				object = factory.getObject();
    			}
    		}
    		catch (FactoryBeanNotInitializedException ex) {
    			throw new BeanCurrentlyInCreationException(beanName, ex.toString());
    		}
    		catch (Throwable ex) {
    			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.
    		//getObject返回的是空值,并且该FactoryBean正在初始化中,则直接抛异常,不接受一个尚未完全初始化的FactoryBean的getObject返回的空值
    		if (object == null) {
    			if (isSingletonCurrentlyInCreation(beanName)) {
    				throw new BeanCurrentlyInCreationException(
    						beanName, "FactoryBean which is currently in creation returned null from getObject");
    			}
    			object = new NullBean();
    		}
    		return object;
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38

    方法4:postProcessObjectFromFactoryBean

    	protected Object postProcessObjectFromFactoryBean(Object object, String beanName) {
    		return applyBeanPostProcessorsAfterInitialization(object, beanName);
    	}
    
    • 1
    • 2
    • 3
    	public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
    			throws BeansException {
    
    		Object result = existingBean;
    		for (BeanPostProcessor processor : getBeanPostProcessors()) {
    			Object current = processor.postProcessAfterInitialization(result, beanName);
    			if (current == null) {
    				return result;
    			}
    			result = current;
    		}
    		return result;
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    获取所有的BeanPostProcessor实现类,调用其postProcessAfterInitialization方法。BeanPostProcessor在前面的文章中
    Spring IOC源码:registerBeanPostProcessors 详解》
    讲解过。

    方法5:markBeanAsCreated

    	protected void markBeanAsCreated(String beanName) {
    		if (!this.alreadyCreated.contains(beanName)) {
    			synchronized (this.mergedBeanDefinitions) {
    				if (!this.alreadyCreated.contains(beanName)) {
    					// Let the bean definition get re-merged now that we're actually creating
    					// the bean... just in case some of its metadata changed in the meantime.
    					//删除RootBeanDefinition信息
    					clearMergedBeanDefinition(beanName);
    					//添加到alreadyCreated缓存中,标识正在创建中
    					this.alreadyCreated.add(beanName);
    				}
    			}
    		}
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    方法6:isDependent

    	protected boolean isDependent(String beanName, String dependentBeanName) {
    		synchronized (this.dependentBeanMap) {
    			return isDependent(beanName, dependentBeanName, null);
    		}
    	}
    
    	private boolean isDependent(String beanName, String dependentBeanName, @Nullable Set<String> alreadySeen) {
    		if (alreadySeen != null && alreadySeen.contains(beanName)) {
    			return false;
    		}
    		//尝试从别名缓存中获取beanName
    		String canonicalName = canonicalName(beanName);
    		//获取依赖canonicalName的beanName集合
    		Set<String> dependentBeans = this.dependentBeanMap.get(canonicalName);
    		if (dependentBeans == null) {
    			return false;
    		}
    		//如果依赖A的集合中包含了dependentBeanName,则证明dependentBeanName依赖beanName
    		if (dependentBeans.contains(dependentBeanName)) {
    			return true;
    		}
    		//递归查找,如果dependentBeanName不在依赖A的集合中,则遍历依赖beanName的依赖,看是否隔代依赖
    		for (String transitiveDependency : dependentBeans) {
    			if (alreadySeen == null) {
    				alreadySeen = new HashSet<>();
    			}
    			alreadySeen.add(beanName);
    			if (isDependent(transitiveDependency, dependentBeanName, alreadySeen)) {
    				return true;
    			}
    		}
    		return false;
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

    这里有一点乱,梳理一下。这个方法的目的是找出beanName的依赖dependentBeanName,是否也依赖beanName,造成循环依赖了,如A依赖B,B也依赖A。如果不存在这种情况,那也有可能是A依赖B,B依赖C,C依赖A这种隔代依赖的,同样也会造成循环依赖的情况,这也就是为什么要遍历一下依赖BeanName的集合与dependentBeanName的依赖关系。

    方法7:registerDependentBean

    	public void registerDependentBean(String beanName, String dependentBeanName) {
    	//通过别名获取真正的beanName
    		String canonicalName = canonicalName(beanName);
    
    		synchronized (this.dependentBeanMap) {
    		//获取依赖canonicalName的beanName集合
    			Set<String> dependentBeans =
    					this.dependentBeanMap.computeIfAbsent(canonicalName, k -> new LinkedHashSet<>(8));
    			//将dependentBeanName添加到依赖beanName的集合中
    			if (!dependentBeans.add(dependentBeanName)) {
    				return;
    			}
    		}
    		//将canonicalName添加到dependentBeanName依赖的beanName集合中
    		synchronized (this.dependenciesForBeanMap) {
    			Set<String> dependenciesForBean =
    					this.dependenciesForBeanMap.computeIfAbsent(dependentBeanName, k -> new LinkedHashSet<>(8));
    			dependenciesForBean.add(canonicalName);
    		}
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    这边又引入了一个跟 dependentBeanMap 类似的缓存,dependenciesForBeanMap:beanName -> beanName 对应的 bean 依赖的所有 bean 的 beanName 集合。

    这两个缓存很容易搞混,举个简单例子:例如 B 依赖了 A,则 dependentBeanMap 缓存中应该存放一对映射:其中 key 为 A,value 为含有 B 的 Set;而 dependenciesForBeanMap 缓存中也应该存放一对映射:其中 key 为:B,value 为含有 A 的 Set。

    方法8:getSingleton

    public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
    		Assert.notNull(beanName, "Bean name must not be null");
    		synchronized (this.singletonObjects) {
    			//尝试从一级缓存中获取
    			Object singletonObject = this.singletonObjects.get(beanName);
    			if (singletonObject == null) {
    				if (this.singletonsCurrentlyInDestruction) {
    					throw new BeanCreationNotAllowedException(beanName,
    							"Singleton bean creation not allowed while singletons of this factory are in destruction " +
    							"(Do not request a bean from a BeanFactory in a destroy method implementation!)");
    				}
    				if (logger.isDebugEnabled()) {
    					logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
    				}
    				//添加到singletonsCurrentlyInCreation缓存中
    				beforeSingletonCreation(beanName);
    				boolean newSingleton = false;
    				boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
    				if (recordSuppressedExceptions) {
    					this.suppressedExceptions = new LinkedHashSet<>();
    				}
    				try {
    					//调用ObjectFactory对象的getObject方法返回实例,getObject方法的实现就是传参时的匿名内部类
    					singletonObject = singletonFactory.getObject();
    					newSingleton = true;
    				}
    				catch (IllegalStateException ex) {
    					// Has the singleton object implicitly appeared in the meantime ->
    					// if yes, proceed with it since the exception indicates that state.
    					singletonObject = this.singletonObjects.get(beanName);
    					if (singletonObject == null) {
    						throw ex;
    					}
    				}
    				catch (BeanCreationException ex) {
    					if (recordSuppressedExceptions) {
    						for (Exception suppressedException : this.suppressedExceptions) {
    							ex.addRelatedCause(suppressedException);
    						}
    					}
    					throw ex;
    				}
    				finally {
    					if (recordSuppressedExceptions) {
    						this.suppressedExceptions = null;
    					}
    					//从singletonsCurrentlyInCreation缓存中移除
    					afterSingletonCreation(beanName);
    				}
    				//添加到一级缓存中,移除二级缓存、三级缓存
    				if (newSingleton) {
    					addSingleton(beanName, singletonObject);
    				}
    			}
    			return singletonObject;
    		}
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57

    singletonsCurrentlyInCreation缓存的作用可以避免出现构造器循环依赖的出现,如果使用构造器创建时,A类的构造函数需要传入B,所以在创建A之前需要先创建B,B构造函数中也需要传入A,所以需要先创建A,这样就出现了循环依赖导致死循环,如果有singletonsCurrentlyInCreation这个缓存的话,就有了A的创建记录,B调用构造方法前如果需要传入A,就先判断A是否正在创建,如果正在创建就抛出异常。构造器方式实例化是没有办法解决循环依赖的,因为每次调用构造函数前都需要先创建入参所需要的实例。

    addSingleton(beanName, singletonObject),见方法9详解
    singletonObject = singletonFactory.getObject(),这个方法比较复杂,放在下篇文章讲解;

    方法9:addSingleton

    	protected void addSingleton(String beanName, Object singletonObject) {
    		synchronized (this.singletonObjects) {
    			//添加到一级缓存中
    			this.singletonObjects.put(beanName, singletonObject);
    			//移除三级缓存
    			this.singletonFactories.remove(beanName);
    			//移除二级缓存
    			this.earlySingletonObjects.remove(beanName);
    			//添加到已经注册的单例对象缓存
    			this.registeredSingletons.add(beanName);
    		}
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    总结

    整理一下getBean方法的流程。
    1、先从缓存中获取实例对象,如果有实例则进行工厂对象解析流程,判断beanName是否带&符号,决定是返回工厂对象本身还是返回真正的实例,如果是返回真正的实例,则调用工厂对象的getObject返回,如果返回值为null,并且在isSingletonCurrentlyInCreation中存在,代表是一个正在创建的bean,不完整的工厂对象,则抛出异常。生成事理后调用BeanPostProcessor的after方法。

    2、如果是原型模式,并且该Bean正在创建中,则抛出异常,避免循环依赖产生,如:A依赖B,B依赖A。A创建后需要注入属性B,则去创建A,由于是原型模式(多例),所以每次都会创建新的对象,创建A,A又会创建B,导致循环依赖的产生。所以B在创建A时,看下容器中是否有在创建的A,有则代表处于循环依赖中,此时抛异常,避免循环依赖产品,所以多例是没办法解决循环依赖问题的。

    3、如果当前beanDefinition缓存中不存在定义,则去父工厂查找,调用父工厂的bean创建流程

    4、获取bean的依赖,在创建前会先实例化此依赖Bean。所以需要判断其依赖是否也依赖其本身,抛出异常避免循环依赖产生。如A依赖B,在创建A时必先创建B,如果B也依赖A,在创建时又会先创建A,这样又导致循环依赖了。所以如果存在bean的依赖也依赖其本身,或者是隔代依赖(A依赖B,B依赖C,C依赖A)这种闭环的也会出问题。

    5、如果是单例模式,则调用走getSingleton方法,参数为ObjectFactory类型的匿名内部类

    6、如果为原型模式,则直接调用createBean方法,创建新的实例

    7、如果不是单例也不是原型模式,则从缓存中获取自定义的Scope,调用其get方法传入ObjectFactory类型的匿名内部类,进行实例创建。

    8、步骤5、步骤6、步骤7创建完成bean对象后,走步骤1进行FactoryBean逻辑处理。

  • 相关阅读:
    代理模式-P19
    Python使用magic判断文件MIME类型
    GPT4不限制使用次数了!GPT5即将推出了!
    白炽灯护眼还是LED护眼?盘点led护眼灯品牌排行
    Windows电脑部署Jellyfin服务端并进行远程访问配置详细教程
    200行代码实现canvas九宫格密码锁
    PIMPL技巧
    Api 接口优化有哪些技巧?
    问答:计算机网络技术是什么?
    SpringBoot整合Neo4j
  • 原文地址:https://blog.csdn.net/weixin_45031612/article/details/128025417