1. 程式人生 > >spring原始碼學習(5.1.0)——Bean的初始化(下)

spring原始碼學習(5.1.0)——Bean的初始化(下)

目錄

前言

結語

前言

上篇部落格主要介紹了createBean方法,Bean的初始化會有三個主要的方法

createBean:初始化Bean,此時還沒有進行屬性填充
populateBean:進行屬性填充
initializeBean:呼叫生命週期回撥
這篇部落格主要介紹populateBean、initializeBean方法

本文難免有錯誤,歡迎大家指出錯誤
 

populateBean

	/**
	 * Populate the bean instance in the given BeanWrapper with the property values
	 * from the bean definition.
	 * @param beanName the name of the bean
	 * @param mbd the bean definition for the bean
	 * @param bw the BeanWrapper with bean instance
	 */
	@SuppressWarnings("deprecation")  // for postProcessPropertyValues
	protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
		if (bw == null) {
			bw為空,說明Bean是一個空物件,空物件卻有需要填充的屬性,丟擲異常
			if (mbd.hasPropertyValues()) {
				throw new BeanCreationException(
						mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
			}
			else {
				// Skip property population phase for null instance.
				跳過空物件
				return;
			}
		}

		// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
		// state of the bean before properties are set. This can be used, for example,
		// to support styles of field injection.
		boolean continueWithPropertyPopulation = true;

		if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
			for (BeanPostProcessor bp : getBeanPostProcessors()) {
				if (bp instanceof InstantiationAwareBeanPostProcessor) {
					InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
					postProcessAfterInstantiation(java.lang.Object bean, java.lang.String beanName)返回物件的型別為Object
					如果該方法返回為null,說明是空物件,就不需要繼續進行屬性填充
					if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
						continueWithPropertyPopulation = false;
						break;
					}
				}
			}
		}

		if (!continueWithPropertyPopulation) {
			return;
		}

		pvs儲存setter依賴注入的屬性的值,第一次初始化時,pvs的值為null
		PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);

		setter依賴注入有兩種方式:
		1、根據Bean的名字
		2、根據Bean的型別
		if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME || mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
			MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
			// Add property values based on autowire by name if applicable.
			if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME) {
				autowireByName(beanName, mbd, bw, newPvs);
			}
			// Add property values based on autowire by type if applicable.
			if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
				autowireByType(beanName, mbd, bw, newPvs);
			}
			通過上面兩個方法,pvs儲存了setter依賴注入的屬性的值
			pvs = newPvs;
		}

		確保存在InstantiationAwareBeanPostProcessor類的例項
		boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
		判斷是否需要依賴檢查
		boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);

		PropertyDescriptor[] filteredPds = null;
		if (hasInstAwareBpps) {
				如果pvs為空,嘗試從RootBeanDefinition中獲取
				if (pvs == null) {
					pvs = mbd.getPropertyValues();
				}
				獲得過濾條件,過濾一部分依賴
				PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
				if (hasInstAwareBpps) {
					for (BeanPostProcessor bp : getBeanPostProcessors()) {
						if (bp instanceof InstantiationAwareBeanPostProcessor) {
							InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
							/*Post-process the given property values before the factory applies them to the given bean.
							*Allows for checking whether all dependencies have been satisfied, 
							*for example based on a "Required" annotation on bean property setters.
							*Also allows for replacing the property values to apply, 
							*typically through creating a new MutablePropertyValues instance based on the original PropertyValues, 
							*adding or removing specific values.
							*/
							pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
							if (pvs == null) {
								return;
							}
						}
					}
				}
				
				if (needsDepCheck) {
					依賴檢查,以確定所有所需依賴都已經初始化
					checkDependencies(beanName, mbd, filteredPds, pvs);
				}
			}
		}
		if (pvs != null) {
			這裡會將依賴注入到對應的屬性中
			applyPropertyValues(beanName, mbd, bw, pvs);
		}
	}

接下來看看自動裝配相關的兩個方法

autowireByName

	/**
	 * Fill in any missing property values with references to
	 * other beans in this factory if autowire is set to "byName".
	 * @param beanName the name of the bean we're wiring up.
	 * Useful for debugging messages; not used functionally.
	 * @param mbd bean definition to update through autowiring
	 * @param bw the BeanWrapper from which we can obtain information about the bean
	 * @param pvs the PropertyValues to register wired objects with
	 */
	protected void autowireByName(
			String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {

		獲得需要進行依賴注入的屬性
		String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
		for (String propertyName : propertyNames) {
			確保容器含有這個Bean的BeanDefinition
			if (containsBean(propertyName)) {
				呼叫getBean函式,獲得例項,若依賴還沒有初始化,則在這裡會初始化
				由於當前Bean已經存在於三級快取,所以可以處理setter迴圈依賴的情況
				Object bean = getBean(propertyName);
				新增到pvs快取中,以便applyPropertyValues函式進行依賴注入
				pvs.add(propertyName, bean);
				儲存beanName與propertyName的依賴關係,這裡會做兩件事
				1、記錄beanName依賴於propertyName
				2、記錄propertyName是beanName的依賴,以便銷燬propertyName例項時,首先銷燬beanName例項
				registerDependentBean(propertyName, beanName);
				if (logger.isTraceEnabled()) {
					logger.trace("Added autowiring by name from bean name '" + beanName +
							"' via property '" + propertyName + "' to bean named '" + propertyName + "'");
				}
			}
			else {
				if (logger.isTraceEnabled()) {
					logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName +
							"' by name: no matching bean found");
				}
			}
		}
	}

autowireByType

	/**
	 * Abstract method defining "autowire by type" (bean properties by type) behavior.
	 * <p>This is like PicoContainer default, in which there must be exactly one bean
	 * of the property type in the bean factory. This makes bean factories simple to
	 * configure for small namespaces, but doesn't work as well as standard Spring
	 * behavior for bigger applications.
	 * @param beanName the name of the bean to autowire by type
	 * @param mbd the merged bean definition to update through autowiring
	 * @param bw the BeanWrapper from which we can obtain information about the bean
	 * @param pvs the PropertyValues to register wired objects with
	 */
	protected void autowireByType(
			String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {

		獲得型別轉換器,用於型別轉換,spring預先定義了一堆型別轉換器,springmvc的handlerAdapter中就有用到spring定義的轉換器
		TypeConverter converter = getCustomTypeConverter();
		if (converter == null) {
			converter = bw;
		}

		Set<String> autowiredBeanNames = new LinkedHashSet<>(4);
		獲得需要依賴的屬性
		String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
		for (String propertyName : propertyNames) {
			try {
				嘗試獲得快取,由於是第一次初始化,所以pd一定為null
				PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
				// Don't try autowiring by type for type Object: never makes sense,
				// even if it technically is a unsatisfied, non-simple property.
				不會為型別為object的屬性進行依賴注入,因為所有的Bean都滿足,肯定會出現衝突
				if (Object.class != pd.getPropertyType()) {
					獲得對應屬性的setter方法的形參
					MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
					// Do not allow eager init for type matching in case of a prioritized post-processor.
					
					boolean eager = !PriorityOrdered.class.isInstance(bw.getWrappedInstance());
					DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
					根據型別從容器獲得對應的依賴,如果有多個Bean滿足條件
					則會根據一系列規則,保證只返回一個依賴
					Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
					if (autowiredArgument != null) {
						新增到pvs快取中,以便applyPropertyValues函式進行依賴注入
						pvs.add(propertyName, autowiredArgument);
					}
					for (String autowiredBeanName : autowiredBeanNames) {
						儲存beanName與propertyName的依賴關係,這裡會做兩件事
						1、記錄beanName依賴於propertyName
						2、記錄propertyName是beanName的依賴,以便銷燬propertyName例項時,首先銷燬beanName例項
						registerDependentBean(autowiredBeanName, beanName);
						if (logger.isTraceEnabled()) {
							logger.trace("Autowiring by type from bean name '" + beanName + "' via property '" +
									propertyName + "' to bean named '" + autowiredBeanName + "'");
						}
					}
					autowiredBeanNames.clear();
				}
			}
			catch (BeansException ex) {
				throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex);
			}
		}
	}

重點在於如何根據型別獲得依賴——resolveDependency

resolveDependency

	@Override
	@Nullable
	public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName,
			@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {

		descriptor.initParameterNameDiscovery(getParameterNameDiscoverer());
		
		getDependencyType會呼叫 Field.getGenericType獲取成員變數宣告型別(包含泛型型別)
        java.util.Optional型別
		if (Optional.class == descriptor.getDependencyType()) {
			將 doResolveDependency返回包裝成 Optional
			return createOptionalDependency(descriptor, requestingBeanName);
		}
		
		處理ObjectFactory或 ObjectProvider型別
		else if (ObjectFactory.class == descriptor.getDependencyType() ||
				ObjectProvider.class == descriptor.getDependencyType()) {
			return new DependencyObjectProvider(descriptor, requestingBeanName);
		}
		
		處理javax.inject.Provider型別
		else if (javaxInjectProviderClass == descriptor.getDependencyType()) {
			return new Jsr330Factory().createDependencyProvider(descriptor, requestingBeanName);
		}
		else {
		
			ContextAnnotationAutowireCandidateResolver實現了 getLazyResolutionProxyIfNecessary
			對於被 @Lazy標識的成員,通過代理支援延遲載入,用於處理生命週期不一致的情況
			Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary(
					descriptor, requestingBeanName);
			if (result == null) {
				一般情況下,會跑到這裡來獲得對應屬性,展開此方法
				result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter);
			}
			return result;
		}
	}

doResolveDependency

	@Nullable
	public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName,
			@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {

		InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor);
		try {
			resolveShortcut函式由ShortcutDependencyDescriptor實現,該方法嘗試通過getBean(String name, Class<T> requiredType)
			方法獲得例項
			Object shortcut = descriptor.resolveShortcut(this);
			if (shortcut != null) {
				return shortcut;
			}

			獲得依賴的型別
			Class<?> type = descriptor.getDependencyType();
			處理@Value註解
			Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor);
			if (value != null) {
				if (value instanceof String) {
					對@value註解的值進行處理
					String strVal = resolveEmbeddedValue((String) value);
					BeanDefinition bd = (beanName != null && containsBean(beanName) ? getMergedBeanDefinition(beanName) : null);
					value = evaluateBeanDefinitionString(strVal, bd);
				}
				獲得型別轉換器
				TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
				依據屬性的型別對@Value註解的值進行型別轉換
				return (descriptor.getField() != null ?
						converter.convertIfNecessary(value, type, descriptor.getField()) :
						converter.convertIfNecessary(value, type, descriptor.getMethodParameter()));
			}
			
			resolveMultipleBeans函式幹了下面幾件事
			1、如果是陣列,則獲取陣列元素型別,查詢匹配該型別的所有bean,返回一個這些bean的陣列;
			2、如果該類可賦給Collection,並且是一個介面,則獲取集合元素型別,查詢匹配該型別的所有bean,返回一個這些bean的集合;
			3、如果該型別是Map(注意是type == Map.class),且key是String型別,則獲取Map的value的型別,
			   查詢匹配該型別的所有bean,這是一個key為bean name、value為bean例項的一個Map,返回這個Map。
			4、容器中所有的例項都會快取到autowiredBeanNames中,用於記錄Bean與Bean之間的依賴關係
			Object multipleBeans = resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter);
			if (multipleBeans != null) {
				return multipleBeans;
			}

			依據型別獲得所有滿足條件的bean
			Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor);
			if (matchingBeans.isEmpty()) {
				如果沒有滿足條件的bean,則判斷是不是有@Require註解,這幾行程式碼說明,沒有找到依賴的情況下
				預設情況下,對應的bean屬性為null
				if (isRequired(descriptor)) {
					raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
				}
				return null;
			}

			String autowiredBeanName;
			Object instanceCandidate;

			如果有多個滿足條件的bean
			if (matchingBeans.size() > 1) {
				1、通過primary屬性來判斷,多個同類型 bean同時配置 primary會拋異常
                2、如果上面沒結果,則通過@Priority註解來篩選
                3、依舊沒有結果,通過候選名稱與成員定義的 beanName/別名匹配(對於按型別匹配來說,這個預設不成立)
				autowiredBeanName = determineAutowireCandidate(matchingBeans, descriptor);
				if (autowiredBeanName == null) {
					if (isRequired(descriptor) || !indicatesMultipleBeans(type)) {
						由於resolveMultipleBeans函式需要滿足一定條件才能進行匹配,所以走到這一步,依賴的型別仍然可能是容器
						如果bean的屬性有@Require註解修飾或者不是陣列、collection、map型別,則拋 NoUniqueBeanDefinitionException異常
						return descriptor.resolveNotUnique(descriptor.getResolvableType(), matchingBeans);
					}
					else {
						// In case of an optional Collection/Map, silently ignore a non-unique case:
						// possibly it was meant to be an empty collection of multiple regular beans
						// (before 4.3 in particular when we didn't even look for collection beans).
						對於容器型別來說,如果不滿足resolveMultipleBeans函式的匹配條件,即使有多個匹配bean,也會返回null
						return null;
					}
				}
				instanceCandidate = matchingBeans.get(autowiredBeanName);
			}
			else {
				// We have exactly one match.
				只有一個匹配結果的情況
				Map.Entry<String, Object> entry = matchingBeans.entrySet().iterator().next();
				autowiredBeanName = entry.getKey();
				instanceCandidate = entry.getValue();
			}

			if (autowiredBeanNames != null) {
				autowiredBeanNames.add(autowiredBeanName);
			}
			if (instanceCandidate instanceof Class) {
				如果是class物件,則對其進行例項化
				instanceCandidate = descriptor.resolveCandidate(autowiredBeanName, type, this);
			}
			Object result = instanceCandidate;
			if (result instanceof NullBean) {
				if (isRequired(descriptor)) {
				這裡還要判斷一次,是因為NullBean也是一個類,也可能滿足型別匹配,
				但是這個類表示null,如果屬性有@Require註解修飾,丟擲異常,
					raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
				}
				result = null;
			}
			if (!ClassUtils.isAssignableValue(type, result)) {
				throw new BeanNotOfRequiredTypeException(autowiredBeanName, type, instanceCandidate.getClass());
			}
			return result;
		}
		finally {
			ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint);
		}
	}

這個方法還可以繼續展開,但礙於精力有限,過一段時間在看,主要是型別匹配相關的方法:

1、findAutowireCandidates(beanName, type, descriptor)
2、resolveShortcut函式由ShortcutDependencyDescriptor實現,該方法嘗試通過getBean(String name, Class<T> requiredType)
    方法獲得例項
    bject shortcut = descriptor.resolveShortcut(this);
3、resolveMultipleBeans函式

applyPropertyValues

	/**
	 * Apply the given property values, resolving any runtime references
	 * to other beans in this bean factory. Must use deep copy, so we
	 * don't permanently modify this property.
	 * @param beanName the bean name passed for better exception information
	 * @param mbd the merged bean definition
	 * @param bw the BeanWrapper wrapping the target object
	 * @param pvs the new property values
	 */
	protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
		pvs為空,沒有需要setter依賴注入的屬性,返回
		if (pvs.isEmpty()) {
			return;
		}

		if (System.getSecurityManager() != null && bw instanceof BeanWrapperImpl) {
			((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());
		}

		MutablePropertyValues mpvs = null;
		List<PropertyValue> original;

		MutablePropertyValues是一個容器,實現了PropertyValues介面,用於儲存setter依賴注入的屬性以及對應的值
		if (pvs instanceof MutablePropertyValues) {
			mpvs = (MutablePropertyValues) pvs;
			mpvs.isConverted用於判斷容器中的屬性值是否進行了型別轉換
			if (mpvs.isConverted()) {
				// Shortcut: use the pre-converted values as-is.
				try {
					如果進行了型別轉換,直接進行setter依賴注入,然後返回
					bw.setPropertyValues(mpvs);
					return;
				}
				catch (BeansException ex) {
					throw new BeanCreationException(
							mbd.getResourceDescription(), beanName, "Error setting property values", ex);
				}
			}
			original = mpvs.getPropertyValueList();
		}
		else {
			original = Arrays.asList(pvs.getPropertyValues());
		}

		經過上述操作,original中儲存了所有屬性以及對應的值
		
		獲得型別轉換器
		TypeConverter converter = getCustomTypeConverter();
		if (converter == null) {
			converter = bw;
		}
		BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);

		// Create a deep copy, resolving any references for values.
		List<PropertyValue> deepCopy = new ArrayList<>(original.size());
		boolean resolveNecessary = false;
		for (PropertyValue pv : original) {
			如果屬性已經進行型別轉換,直接儲存到容器中
			if (pv.isConverted()) {
				deepCopy.add(pv);
			}
			否則,進行型別轉換
			else {
				String propertyName = pv.getName();
				Object originalValue = pv.getValue();
				以下這句程式碼用C++來說,就是將指標指向某一個物件,官方文件的解釋是:
				Given a PropertyValue, return a value, resolving any references to other beans in the factory if necessary. The value could be:
				1、A BeanDefinition, which leads to the creation of a corresponding new bean instance. Singleton flags and names of such "inner beans" are always ignored: Inner beans are anonymous prototypes.
				2、A RuntimeBeanReference, which must be resolved.
				3、A ManagedList. This is a special collection that may contain RuntimeBeanReferences or Collections that will need to be resolved.
				4、A ManagedSet. May also contain RuntimeBeanReferences or Collections that will need to be resolved.
				5、A ManagedMap. In this case the value may be a RuntimeBeanReference or Collection that will need to be resolved.
				   An ordinary object or null, in which case it's left alone.

				Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
				Object convertedValue = resolvedValue;
				
				對屬性進行型別轉換的條件
				1、屬性可寫
				2、非指示索引,即person.addresses[0]
				3、非巢狀屬性,即foo.bar
				2與3出現在xml配置中
				boolean convertible = bw.isWritableProperty(propertyName) &&
						!PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
				if (convertible) {
					進行型別轉換,物件的儲存結構可能會發生變化,需要看一看convertForProperty
					convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter);
				}
				
				
				經過上述操作,所有的型別都進行了型別轉換,接下來將它們儲存到BeanDefinition中,
				以便下次初始化時,不需要再次進行型別轉換
				// Possibly store converted value in merged bean definition,
				// in order to avoid re-conversion for every created bean instance.
				沒有進行型別轉換
				if (resolvedValue == originalValue) {
					if (convertible) {
						pv.setConvertedValue(convertedValue);
					}
					deepCopy.add(pv);
				}
				進行了型別轉換,滿足下列條件時,儲存到BeanDefinition中:
				1、convertible為true(看上文的條件)
				2、originalValue繼承了TypeStringValue(這個類內部儲存了源物件以及型別轉換後的物件(或型別))
				3、該物件非動態,關於什麼是動態,原始碼中是這麼解釋的:as containing an expression and hence not being subject to caching.
				   我的理解是含有spring EL
				4、轉換後的型別不是集合、陣列型別,為什麼陣列、集合型別不快取呢?
				   我的理解是每次例項化時,集合以及陣列中的成員都可能發生變化
				  (例如scope為原型的物件,可能例項化多次,而且scope為原型的物件生命週期不受容器控制),故不快取
				else if (convertible && originalValue instanceof TypedStringValue &&
						!((TypedStringValue) originalValue).isDynamic() &&
						!(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) {
					pv.setConvertedValue(convertedValue);
					deepCopy.add(pv);
				}
				不滿足if、else if中的條件,則不儲存到BeanDefinition中
				else {
					resolveNecessary = true;
					deepCopy.add(new PropertyValue(pv, convertedValue));
				}
			}
		}
		if (mpvs != null && !resolveNecessary) {
			設定以進行型別轉換標誌,下次初始化時,就不需要在進行型別轉換
			mpvs.setConverted();
		}

		// Set our (possibly massaged) deep copy.
		try {
			設定屬性值
			bw.setPropertyValues(new MutablePropertyValues(deepCopy));
		}
		catch (BeansException ex) {
			throw new BeanCreationException(
					mbd.getResourceDescription(), beanName, "Error setting property values", ex);
		}
	}
}
	

上述程式碼提到了型別轉換,這種型別轉換並不是子類與父類之間的轉換,而是不同儲存結構的類之間的轉換,例如將Date轉換為Calender,spring定義了許多型別轉換器,springmvc就是利用spring的型別轉換器實現http與java物件的相互轉換的,spring的型別轉換器非常的多,這裡就不一一列舉了

至此,物件的依賴注入就完成了,接下來,進行生命週期回撥,為需要生成代理的物件生成代理

initializeBean

	/**
	 * Initialize the given bean instance, applying factory callbacks
	 * as well as init methods and bean post processors.
	 * <p>Called from {@link #createBean} for traditionally defined beans,
	 * and from {@link #initializeBean} for existing bean instances.
	 * @param beanName the bean name in the factory (for debugging purposes)
	 * @param bean the new bean instance we may need to initialize
	 * @param mbd the bean definition that the bean was created with
	 * (can also be {@code null}, if given an existing bean instance)
	 * @return the initialized bean instance (potentially wrapped)
	 * @see BeanNameAware
	 * @see BeanClassLoaderAware
	 * @see BeanFactoryAware
	 * @see #applyBeanPostProcessorsBeforeInitialization
	 * @see #invokeInitMethods
	 * @see #applyBeanPostProcessorsAfterInitialization
	 */
	protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
		if (System.getSecurityManager() != null) {
			AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
				invokeAwareMethods(beanName, bean);
				return null;
			}, getAccessControlContext());
		}
		else {
			設定BeanDefiniton中的部分值
			invokeAwareMethods(beanName, bean);
		}

		Object wrappedBean = bean;
		if (mbd == null || !mbd.isSynthetic()) {
		呼叫BeanPostProcessorsBeforeInitialization,在呼叫init函式之前對bean進行處理
			wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
		}

		try {
			呼叫init函式,這個方法內部會通過解析得到需要執行的init函式
			invokeInitMethods(beanName, wrappedBean, mbd);
		}
		catch (Throwable ex) {
			throw new BeanCreationException(
					(mbd != null ? mbd.getResourceDescription() : null),
					beanName, "Invocation of init method failed", ex);
		}
		if (mbd == null || !mbd.isSynthetic()) {
			呼叫BeanPostProcessorsAfterInitialization,此處會為需要生成代理的物件生成代理
			wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
		}

		return wrappedBean;
	}

結語

至此,spring的IOC容器的初始化的粗略框架就總結完了,看完這些程式碼,再來看看什麼是IOC,簡單來說,IOC就是一個快取,可以快取spring建立的例項,並且,IOC能幫助我們建立Bean,並管理單例Bean的生命週期,非單例Bean由於不會被spring快取,spring自然就不會管理其生命週期