Spring Ioc源碼分析系列--Bean實例化過程(二)

来源:https://www.cnblogs.com/codegitz/archive/2022/05/31/16331774.html
-Advertisement-
Play Games

Spring Ioc源碼分析系列--Bean實例化過程(二) 前言 上篇文章Spring Ioc源碼分析系列--Bean實例化過程(一)簡單分析了getBean()方法,還記得分析了什麼嗎?不記得了才是正常的,記住了才是怪人,忘記了可以回去翻翻,翻不翻都沒事, 反正最後都會忘了。 這篇文章是給上篇填 ...


Spring Ioc源碼分析系列--Bean實例化過程(二)

前言

上篇文章Spring Ioc源碼分析系列--Bean實例化過程(一)簡單分析了getBean()方法,還記得分析了什麼嗎?不記得了才是正常的,記住了才是怪人,忘記了可以回去翻翻,翻不翻都沒事, 反正最後都會忘了。

這篇文章是給上篇填坑的,上篇分析到真正創建Bean的createBean(beanName, mbd, args)就沒有繼續深入去分析了,繞得太深,說不清楚。那麼這一篇,就續上這個口子,去分析createBean(beanName, mbd, args)方法。

源碼分析

話不多說,我們直接來到createBean(beanName, mbd, args)方法的源碼。具體的實現是在AbstractAutowireCapableBeanFactory#createBean(beanName, mbd, args)里,可以直接定位到這裡。

createBean()方法

跟進代碼查看,這個方法也比較簡單,主要分為了以下幾點:

  • 初始化化Class對象。調用resolveBeanClass(mbd, beanName)方法獲取class對象,這裡會去解析類全限定名,最終是通過反射方法Class<?> resolvedClass = ClassUtils.forName(className, classLoader)獲取Class對象。
  • 檢查覆蓋方法。對應的是mbdToUse.prepareMethodOverrides()方法,這裡會對一些重載方法進行標記預處理,如果同方法名的方法只存在一個,那麼會將覆蓋標記為未重載,以避免 arg 類型檢查的開銷。
  • 應用後置處理器。在實例化對象前,會經過後置處理器處理,這個後置處理器的提供了一個短路機制,就是可以提前結束整個Bean的生命周期,直接從這裡返回一個Bean。
  • 創建Bean。調用doCreateBean()方法進行Bean的創建,在Spring裡面,帶有do開頭的一般是真正幹活的方法,所以Ioc創建Bean到這裡,才是真正要到幹活的地方了。

我們庖丁解牛先把方法不同的功能按照邏輯拆分了,那接下來,就詳細分析一下每個部分。

	/**
	 * Central method of this class: creates a bean instance,
	 * populates the bean instance, applies post-processors, etc.
	 *
	 * 此類的中心方法:創建 bean 實例、填充 bean 實例、應用後處理器等。
	 *
	 * @see #doCreateBean
	 */
	@Override
	protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
			throws BeanCreationException {

		if (logger.isTraceEnabled()) {
			logger.trace("Creating instance of bean '" + beanName + "'");
		}
		RootBeanDefinition mbdToUse = mbd;

		// Make sure bean class is actually resolved at this point, and
		// clone the bean definition in case of a dynamically resolved Class
		// which cannot be stored in the shared merged bean definition.
		//鎖定class ,根據設置的 class 屬性或者根據 className 來解析 Class
		// 解析得到beanClass,為什麼需要解析呢?如果是從XML中解析出來的標簽屬性肯定是個字元串嘛
		// 所以這裡需要載入類,得到Class對象
		Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
		if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
			mbdToUse = new RootBeanDefinition(mbd);
			mbdToUse.setBeanClass(resolvedClass);
		}

		// Prepare method overrides.驗證及準備覆蓋的方法
		// 對XML標簽中定義的lookUp屬性進行預處理,
		// 如果只能根據名字找到一個就標記為非重載的,這樣在後續就不需要去推斷到底是哪個方法了,
		// 對於@LookUp註解標註的方法是不需要在這裡處理的,
		// AutowiredAnnotationBeanPostProcessor會處理這個註解
		try {
			mbdToUse.prepareMethodOverrides();
		}
		catch (BeanDefinitionValidationException ex) {
			throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
					beanName, "Validation of method overrides failed", ex);
		}

		try {
			// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
			//給BeanPostProcessors一個露臉的機會
			// 在實例化對象前,會經過後置處理器處理
			// 這個後置處理器的提供了一個短路機制,就是可以提前結束整個Bean的生命周期,直接從這裡返回一個Bean
			// 不過我們一般不會這麼做,它的另外一個作用就是對AOP提供了支持,
			// 在這裡會將一些不需要被代理的Bean進行標記,就本IoC系列文章而言,你可以暫時理解它沒有起到任何作用
			Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
			//若果有自定義bean則直接返回了bean,不會再走後續的doCreateBean方法
			if (bean != null) {
				return bean;
			}
		}
		catch (Throwable ex) {
			throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
					"BeanPostProcessor before instantiation of bean failed", ex);
		}

		try {
			// 不存在提前初始化的操作,開始正常的創建流程
			// doXXX方法,真正幹活的方法,doCreateBean,真正創建Bean的方法
			Object beanInstance = doCreateBean(beanName, mbdToUse, args);
			if (logger.isTraceEnabled()) {
				logger.trace("Finished creating instance of bean '" + beanName + "'");
			}
			return beanInstance;
		}
		catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
			// 省略部分異常..
		}
		}
	}

初始化Class對象

很顯然初始化Class對象的代碼在resolveBeanClass(mbd, beanName)方法里,跟進代碼查看。

	/**
	 * Resolve the bean class for the specified bean definition,
	 * resolving a bean class name into a Class reference (if necessary)
	 * and storing the resolved Class in the bean definition for further use.
	 *
	 * 為指定的 bean 定義解析 bean 類,將 bean 類名稱解析為 Class 引用(如果需要)並將解析的 Class 存儲在 bean 定義中以供進一步使用。
	 *
	 * @param mbd the merged bean definition to determine the class for
	 * @param beanName the name of the bean (for error handling purposes)
	 * @param typesToMatch the types to match in case of internal type matching purposes
	 * (also signals that the returned {@code Class} will never be exposed to application code)
	 *       在內部類型匹配的情況下要匹配的類型(也表示返回的 {@code Class} 永遠不會暴露給應用程式代碼)
	 * @return the resolved bean class (or {@code null} if none)
	 * @throws CannotLoadBeanClassException if we failed to load the class
	 */
	@Nullable
	protected Class<?> resolveBeanClass(final RootBeanDefinition mbd, String beanName, final Class<?>... typesToMatch)
			throws CannotLoadBeanClassException {

		try {
			// 如果已經創建過,直接返回
			if (mbd.hasBeanClass()) {
				return mbd.getBeanClass();
			}
			if (System.getSecurityManager() != null) {
				return AccessController.doPrivileged((PrivilegedExceptionAction<Class<?>>) () ->
					doResolveBeanClass(mbd, typesToMatch), getAccessControlContext());
			}
			else {
				// 否則進行創建
				return doResolveBeanClass(mbd, typesToMatch);
			}
		}
		catch (PrivilegedActionException pae) {
			// 省略部分異常處理
		}
	}

跟進doResolveBeanClass(mbd, typesToMatch)方法,我們這裡傳入的typesToMatch參數對象數組為空,所以不會走排除部分類的邏輯,接下來是使用evaluateBeanDefinitionString()方法計算表達式如果傳入的className有占位符,會在這裡被解析,最終正常我們會走到mbd.resolveBeanClass(beanClassLoader)方法里。

	private Class<?> doResolveBeanClass(RootBeanDefinition mbd, Class<?>... typesToMatch)
			throws ClassNotFoundException {

		// 獲取類載入器
		ClassLoader beanClassLoader = getBeanClassLoader();
		ClassLoader dynamicLoader = beanClassLoader;
		boolean freshResolve = false;

		if (!ObjectUtils.isEmpty(typesToMatch)) {
			// When just doing type checks (i.e. not creating an actual instance yet),
			// use the specified temporary class loader (e.g. in a weaving scenario).
			// 當只是進行類型檢查(即尚未創建實際實例)時,請使用指定的臨時類載入器(例如在編織場景中)。
			ClassLoader tempClassLoader = getTempClassLoader();
			if (tempClassLoader != null) {
				dynamicLoader = tempClassLoader;
				freshResolve = true;
				if (tempClassLoader instanceof DecoratingClassLoader) {
					DecoratingClassLoader dcl = (DecoratingClassLoader) tempClassLoader;
					for (Class<?> typeToMatch : typesToMatch) {
						dcl.excludeClass(typeToMatch.getName());
					}
				}
			}
		}

		String className = mbd.getBeanClassName();
		if (className != null) {
			Object evaluated = evaluateBeanDefinitionString(className, mbd);
			if (!className.equals(evaluated)) {
				// A dynamically resolved expression, supported as of 4.2...
				if (evaluated instanceof Class) {
					return (Class<?>) evaluated;
				}
				else if (evaluated instanceof String) {
					className = (String) evaluated;
					freshResolve = true;
				}
				else {
					throw new IllegalStateException("Invalid class name expression result: " + evaluated);
				}
			}
			if (freshResolve) {
				// When resolving against a temporary class loader, exit early in order
				// to avoid storing the resolved Class in the bean definition.
				// 當針對臨時類載入器解析時,請提前退出以避免將解析的類存儲在 bean 定義中。
				if (dynamicLoader != null) {
					try {
						// 使用臨時動態載入器載入 class 對象
						return dynamicLoader.loadClass(className);
					}
					catch (ClassNotFoundException ex) {
						if (logger.isTraceEnabled()) {
							logger.trace("Could not load class [" + className + "] from " + dynamicLoader + ": " + ex);
						}
					}
				}
				// 反射載入 class 對象
				return ClassUtils.forName(className, dynamicLoader);
			}
		}

		// Resolve regularly, caching the result in the BeanDefinition...
		// 正常解析,將結果緩存在 BeanDefinition...
		return mbd.resolveBeanClass(beanClassLoader);
	}

跟進mbd.resolveBeanClass(beanClassLoader)方法,可以看到這裡就是使用反射初始化Class對象,然後緩存在BeanDefinition中。到這裡,已經完成了從一個字元串的類名到一個Class對象的轉換了,我們已經得到了一個可以使用的Class對象。

	/**
	 * Determine the class of the wrapped bean, resolving it from a
	 * specified class name if necessary. Will also reload a specified
	 * Class from its name when called with the bean class already resolved.
	 *
	 * 確定被包裝的 bean 的類,必要時從指定的類名解析它。當使用已解析的 bean 類調用時,還將從其名稱中重新載入指定的類。
	 *
	 * @param classLoader the ClassLoader to use for resolving a (potential) class name
	 * @return the resolved bean class
	 * @throws ClassNotFoundException if the class name could be resolved
	 */
	@Nullable
	public Class<?> resolveBeanClass(@Nullable ClassLoader classLoader) throws ClassNotFoundException {
		String className = getBeanClassName();
		if (className == null) {
			return null;
		}
		Class<?> resolvedClass = ClassUtils.forName(className, classLoader);
		this.beanClass = resolvedClass;
		return resolvedClass;
	}

檢查覆蓋方法

初始化class對象已經完成了,接下來會去處理重載方法,處理的邏輯在mbdToUse.prepareMethodOverrides()方法里。

摘取《Spring源碼深度解析》裡面的一段話:

很多讀者可能會不知道這個方法的作用,因為在 Spring 的配置裡面根本就沒有諸如 override-method 之類的配置, 那麼這個方法到底是乾什麼用的呢? 其實在 Spring 中確實沒有 override-method 這樣的配置,但是在 Spring 配置中是存在 lookup-methodreplace-method 的,而這兩個配置的載入其實就是將配置統一存放在 BeanDefinition 中的 methodOverrides 屬性里,而這個函數的操作其實也就是針對於這兩個配置的。

lookup-method通常稱為獲取器註入,spring in action 中對它的描述是,一種特殊的方法註入,它是把一個方法聲明為返回某種類型的 bean,而實際要返回的 bean 是在配置文件裡面配置的,可用在設計可插拔的功能上,解除程式依賴。 這裡會對一些重載方法進行標記預處理,如果同方法名的方法只存在一個,那麼會將覆蓋標記為未重載,以避免 arg 類型檢查的開銷。

這種騷操作我們基本是不會使用的,所以簡單看一下代碼,淺嘗輒止,有興趣可以去翻翻。

	/**
	 * Validate and prepare the method overrides defined for this bean.
	 * Checks for existence of a method with the specified name.
	 *
	 * 驗證並準備為此 bean 定義的方法覆蓋。檢查具有指定名稱的方法是否存在。
	 *
	 * @throws BeanDefinitionValidationException in case of validation failure
	 */
	public void prepareMethodOverrides() throws BeanDefinitionValidationException {
		// Check that lookup methods exist and determine their overloaded status.
		// 檢查查找方法是否存在並確定它們的重載狀態。
		if (hasMethodOverrides()) {
			getMethodOverrides().getOverrides().forEach(this::prepareMethodOverride);
		}
	}

可以看到這裡就獲取所有methodOverrides,然後遍歷去調用prepareMethodOverride()方法,跟進prepareMethodOverride()方法。可以看到這裡就是做個簡單的標記。

	/**
	 * Validate and prepare the given method override.
	 * Checks for existence of a method with the specified name,
	 * marking it as not overloaded if none found.
	 *
	 * 驗證並準備給定的方法覆蓋。檢查具有指定名稱的方法是否存在,如果沒有找到,則將其標記為未重載。
	 *
	 * @param mo the MethodOverride object to validate
	 * @throws BeanDefinitionValidationException in case of validation failure
	 */
	protected void prepareMethodOverride(MethodOverride mo) throws BeanDefinitionValidationException {
		int count = ClassUtils.getMethodCountForName(getBeanClass(), mo.getMethodName());
		if (count == 0) {
			throw new BeanDefinitionValidationException(
					"Invalid method override: no method with name '" + mo.getMethodName() +
					"' on class [" + getBeanClassName() + "]");
		}
		else if (count == 1) {
			// Mark override as not overloaded, to avoid the overhead of arg type checking.
			// 將覆蓋標記為未重載,以避免 arg 類型檢查的開銷。
			mo.setOverloaded(false);
		}
	}

應用後置處理器

在實例化對象前,會經過後置處理器處理,這個後置處理器的提供了一個短路機制,就是可以提前結束整個Bean的生命周期,直接從這裡返回一個Bean。不過我們一般不會這麼做,它的另外一個作用就是對AOP提供了支持,在這裡會將一些不需要被代理的Bean進行標記,就本IoC系列文章而言,你可以暫時理解它沒有起到任何作用。

跟進代碼resolveBeforeInstantiation(beanName, mbdToUse)查看。

	/**
	 * Apply before-instantiation post-processors, resolving whether there is a
	 * before-instantiation shortcut for the specified bean.
	 *
	 * 應用實例化前後處理器,解析指定 bean 是否存在實例化前快捷方式。
	 * 實例化前的快捷方式的意思這裡可能會直接返回一個定義的代理,而不需要在把目標類初始化
	 *
	 * @param beanName the name of the bean
	 * @param mbd the bean definition for the bean
	 * @return the shortcut-determined bean instance, or {@code null} if none
	 */
	//註意單詞Instantiation和Initialization區別
	@Nullable
	protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
		Object bean = null;
		if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
			// Make sure bean class is actually resolved at this point.
			if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
				// 確定給定的 bean 的類型
				Class<?> targetType = determineTargetType(beanName, mbd);
				if (targetType != null) {
					// 提供一個提前初始化的時機,這裡會直接返回一個實例對象
					bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
					if (bean != null) {
						// 如果提前初始化成功,則執行 postProcessAfterInitialization() 方法,註意單詞Instantiation和Initialization區別
						// 關於這一塊的邏輯,細心的一點的會發現,這裡漏了實例化後置處理、初始化前置處理這兩個方法。
						// 而是在提前返回對象後,直接執行了初始化後置處理器就完成了bean的整個流程,
						// 相當於是提供了一個短路的操作,不再經過Spring提供的繁雜的各種處理
						bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
					}
				}
			}
			// 設置是否已經提前實例化
			mbd.beforeInstantiationResolved = (bean != null);
		}
		return bean;
	}

跟進applyBeanPostProcessorsBeforeInstantiation()代碼查看。這裡只要有一個 InstantiationAwareBeanPostProcessor 返回的結果不為空,則直接返回,說明多個 InstantiationAwareBeanPostProcessor 只會生效靠前的一個,註意單詞Instantiation和Initialization區別

	/**
	 * spring bean 初始化流程
	 * Bean 初始化(Initialization)
	 * 1.@PoseConstruct 方法
	 * 2.實現InitializingBean 介面的afterPropertiesSet()方法
	 * 3.自定義初始化方法
	 */
	@Nullable
	protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {
		for (BeanPostProcessor bp : getBeanPostProcessors()) {
			if (bp instanceof InstantiationAwareBeanPostProcessor) {
				InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
				Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
				// 如果為空,表示不作任何調整
				// 這裡只要有一個 InstantiationAwareBeanPostProcessor 返回的結果不為空,則直接返回,
				// 說明多個 InstantiationAwareBeanPostProcessor 只會生效靠前的一個
				if (result != null) {
					return result;
				}
			}
		}
		return null;
	}

跟進applyBeanPostProcessorsAfterInitialization()方法,邏輯跟上面的是類似的,註意單詞Instantiation和Initialization區別

	@Override
	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;
	}

創建Bean

經過上面的步驟,有驚無險,我們來到了doCreateBean(beanName, mbdToUse, args)方法,這是真正進行Bean創建的地方,所以這裡才是真的進入正文,前面都是打醬油走走過程。

當經歷過 resolveBeforelnstantiation() 方法後,程式有兩個選擇 ,如果創建了代理或者說重寫了 InstantiationAwareBeanPostProcessorpostProcessBeforelnstantiation() 方法併在方法 postProcessBeforelnstantiation() 中改變了 bean, 則直接返回就可以了 , 否則需要進行常規 bean 的創建。 而這常規 bean 的創建就是在 doCreateBean() 中完成的。

直接跟進doCreateBean()代碼查看,代碼很長,你忍一下。

	/**
	 * Actually create the specified bean. Pre-creation processing has already happened
	 * at this point, e.g. checking {@code postProcessBeforeInstantiation} callbacks.
	 * <p>Differentiates between default bean instantiation, use of a
	 * factory method, and autowiring a constructor.
	 *
	 * 實際創建指定的bean。
	 * 此時已經進行了預創建處理,例如檢查 {@code postProcessBeforeInstantiation} 回調。
	 * <p>區分預設 bean 實例化、使用工廠方法和自動裝配構造函數。
	 *
	 * @param beanName the name of the bean
	 * @param mbd the merged bean definition for the bean
	 * @param args explicit arguments to use for constructor or factory method invocation
	 * @return a new instance of the bean
	 * @throws BeanCreationException if the bean could not be created
	 * @see #instantiateBean
	 * @see #instantiateUsingFactoryMethod
	 * @see #autowireConstructor
	 */
	protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
			throws BeanCreationException {
		// 這個方法真正創建了Bean,創建一個Bean會經過 創建對象 > 依賴註入 > 初始化
		// 這三個過程,在這個過程中,BeanPostProcessor會穿插執行,

		// Instantiate the bean.
		BeanWrapper instanceWrapper = null;
		if (mbd.isSingleton()) {
			instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
		}
		if (instanceWrapper == null) {
			//根據指定bean使用對應的策略創建新的實例,如工廠方法,構造函數自動註入,簡單初始化
			// 這裡真正的創建了對象
			instanceWrapper = createBeanInstance(beanName, mbd, args);
		}
		final Object bean = instanceWrapper.getWrappedInstance();
		Class<?> beanType = instanceWrapper.getWrappedClass();
		if (beanType != NullBean.class) {
			mbd.resolvedTargetType = beanType;
		}

		// Allow post-processors to modify the merged bean definition.

		// 按照官方的註釋來說,這個地方是Spring提供的一個擴展點,
		// 對程式員而言,我們可以通過一個實現了MergedBeanDefinitionPostProcessor的後置處理器
		// 來修改bd中的屬性,從而影響到後續的Bean的生命周期
		// 不過官方自己實現的後置處理器並沒有去修改bd,
		// 而是調用了applyMergedBeanDefinitionPostProcessors方法
		// 這個方法名直譯過來就是-應用合併後的bd,也就是說它這裡只是對bd做了進一步的使用而沒有真正的修改
		synchronized (mbd.postProcessingLock) {
			// bd只允許被處理一次
			if (!mbd.postProcessed) {
				try {
					// 應用合併後的bd
					applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
				}
				catch (Throwable ex) {
					throw new BeanCreationException(mbd.getResourceDescription(), beanName,
							"Post-processing of merged bean definition failed", ex);
				}
				// 標註這個bd已經被MergedBeanDefinitionPostProcessor的後置處理器處理過
				// 那麼在第二次創建Bean的時候,不會再次調用applyMergedBeanDefinitionPostProcessors
				mbd.postProcessed = true;
			}
		}

		// Eagerly cache singletons to be able to resolve circular references
		// even when triggered by lifecycle interfaces like BeanFactoryAware.
		//是否需要提前暴露mbd.isSingleton() && this.allowCircularReferences &&
		//				isSingletonCurrentlyInCreation(beanName)
		boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
				isSingletonCurrentlyInCreation(beanName));
		if (earlySingletonExposure) {
			if (logger.isTraceEnabled()) {
				logger.trace("Eagerly caching bean '" + beanName +
						"' to allow for resolving potential circular references");
			}
			//為避免後期迴圈依賴,可以在bean初始化完成前將創建實例的ObjectFactory加入工廠
			//getEarlyBeanReference對bean再一次依賴引用,主要應用SmartInstantiationAwareBeanPostProcessor
			//其中我們熟悉的AOP就是在這裡將advice動態織入bean中,若沒有則直接返回bean,不做任何處理
			addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
		}

		// Initialize the bean instance.
		// 初始化實例
		Object exposedObject = bean;
		try {
			//對bean進行填充,對各個屬性進行註入,可能存在依賴其他bean的屬性,則會遞歸初始化依賴bean
			populateBean(beanName, mbd, instanceWrapper);
			//調用初始化方法
			exposedObject = initializeBean(beanName, exposedObject, mbd);
		}
		catch (Throwable ex) {
			if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
				throw (BeanCreationException) ex;
			}
			else {
				throw new BeanCreationException(
						mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
			}
		}

		if (earlySingletonExposure) {
			Object earlySingletonReference = getSingleton(beanName, false);
			//earlySingletonReference只有在檢測到迴圈依賴的情況下才不為空
			if (earlySingletonReference != null) {
				//如果exposedObject沒有在初始化方法中被改變,也就是沒有被增強
				if (exposedObject == bean) {
					exposedObject = earlySingletonReference;
				}
				else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
					String[] dependentBeans = getDependentBeans(beanName);
					Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
					//檢測依賴
					for (String dependentBean : dependentBeans) {
						if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
							actualDependentBeans.add(dependentBean);
						}
					}
					/**
					 * 因為bean創建完成後,其依賴的bean也一定是創建完成的
					 * 如果actualDependentBeans不為空,則說明依賴的bean還沒有被完全創建好
					 * 也就是說還存在迴圈依賴
					 */
					if (!actualDependentBeans.isEmpty()) {
						throw new BeanCurrentlyInCreationException(beanName,
								"Bean with name '" + beanName + "' has been injected into other beans [" +
								StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
								"] in its raw version as part of a circular reference, but has eventually been " +
								"wrapped. This means that said other beans do not use the final version of the " +
								"bean. This is often the result of over-eager type matching - consider using " +
								"'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
					}
				}
			}
		}

		// Register bean as disposable.
		try {
			//根據scope註冊bean
			registerDisposableBeanIfNecessary(beanName, bean, mbd);
		}
		catch (BeanDefinitionValidationException ex) {
			throw new BeanCreationException(
					mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
		}

		return exposedObject;
	}

分析一下這個函數設計思路:

  • 如果是單例則需要首先清除緩存。
  • 實例化 bean ,將 BeanDefinition 轉換為 BeanWrapper。 轉換是一個複雜的過程,但是我們可以嘗試概括大致的功能,如下所示。
    • 如果存在工廠方法則使用工廠方法進行實例化。
    • 如果一個類有多個構造函數,每個構造函數都有不同的參數,所以需要根據參數鎖定構造 函數併進行實例化。
    • 如果既不存在工廠方法也不存在帶有參數的構造函數,則使用預設的構造函數進行 bean 的實例化。
  • MergedBeanDefinitionPostProcessor的應用。 bean 合併後的處理, Autowired 註解正是通過此方法實現諸如類型的預解析。
  • 依賴處理。 在 Spring 中會有迴圈依賴的情況,例如,當 A 中含有 B 的屬性,而 B 中又含有 A 的屬性 時就會構成一個迴圈依賴,此時如果 A 和 B 都是單例,那麼在 Spring 中的處理方式就是當創建 B 的時候,涉及自動註入 A 的步驟,並不是直接去再次創建 A,而是通過放入緩存中的 ObjectFactory 來創建實例,這樣就解決了迴圈依賴的問題。
  • 屬性填充。 將所有屬性填充至 bean 的實例中。
  • 調用初始化方法。在屬性填充完成後,這裡會進行初始化方法的調用。
  • 迴圈依賴檢查。 之前有提到過,在 Sping 中解決迴圈依賴只對單例有效,而對於 prototype 的 bean, Spring 沒有好的解決辦法,唯一要做的就是拋出異常。 在這個步驟裡面會檢測已經載入的 bean 是否 已經出現了依賴迴圈,並判斷是再需要拋出異常。
  • 註冊 DisposableBean。 如果配置了 destroy-method,這裡需要註冊以便於在銷毀時候調用。
  • 完成創建井返回。

可以看到上面的步驟非常的繁瑣,每一步驟都使用了大量的代碼來完成其功能,最複雜也是最難以理解的當屬迴圈依賴的處理,在真正進入 doCreateBean() 前我們有必要先瞭解下迴圈依賴,這裡會在下一篇文章Spring Ioc源碼分析系列--自動註入迴圈依賴的處理圖文並茂去分析。

下麵就按照上述的點逐個分析,接下來肯定是枯燥無味的,那開始吧。

清除factoryBeanInstanceCache緩存

首先如果是單例,會到factoryBeanInstanceCache中獲取是否存在緩存,如果有這裡就會從緩存里獲取一個instanceWrapper,不需要再去走複雜的創建流程了。

對應代碼如下:

		if (mbd.isSingleton()) {
			// 你可以暫時理解為,這個地方返回的就是個null
			instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
		}
實例化 bean

又到了實例化bean,是不是反反覆復看了很多次,到底哪裡才真的創建一個bean,別慌,這裡真的是真正創建bean的地方了,再套娃就是狗。

跟進createBeanInstance(beanName, mbd, args)方法。這個方法幹了哪幾件事?

  • 首先嘗試調用obtainFromSupplier()實例化bean
  • 嘗試調用instantiateUsingFactoryMethod()實例化bean
  • 根據給定參數推斷構造函數實例化bean
  • 以上均無,則使用預設構造函數實例化bean
	/**
	 * Create a new instance for the specified bean, using an appropriate instantiation strategy:
	 * factory method, constructor autowiring, or simple instantiation.
	 *
	 * 使用適當的實例化策略為指定的 bean 創建一個新實例:工廠方法、構造函數自動裝配或簡單實例化。
	 *
	 * @param beanName the name of the bean
	 * @param mbd the bean definition for the bean
	 * @param args explicit arguments to use for constructor or factory method invocation
	 * @return a BeanWrapper for the new instance
	 * @see #obtainFromSupplier
	 * @see #instantiateUsingFactoryMethod
	 * @see #autowireConstructor
	 * @see #instantiateBean
	 */
	protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
		// Make sure bean class is actually resolved at this point.
		// 確保此時實際解析了 bean 類。
		Class<?> beanClass = resolveBeanClass(mbd, beanName);

		if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
			throw new BeanCreationException(mbd.getResourceDescription(), beanName,
					"Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
		}
		// 通過bd中提供的instanceSupplier來獲取一個對象
		// 正常bd中都不會有這個instanceSupplier屬性,這裡也是Spring提供的一個擴展點,但實際上不常用
		Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
		if (instanceSupplier != null) {
			return obtainFromSupplier(instanceSupplier, beanName);
		}

		//如果工廠方法不為null,則使用工廠方法初始化策略
		// bd中提供了factoryMethodName屬性,那麼要使用工廠方法的方式來創建對象,
		// 工廠方法又會區分靜態工廠方法跟實例工廠方法
		if (mbd.getFactoryMethodName() != null) {
			return instantiateUsingFactoryMethod(beanName, mbd, args);
		}

		// Shortcut when re-creating the same bean...
		// 在原型模式下,如果已經創建過一次這個Bean了,那麼就不需要再次推斷構造函數了
		// 是否推斷過構造函數
		boolean resolved = false;
		// 構造函數是否需要進行註入
		boolean autowireNecessary = false;
		if (args == null) {
			synchronized (mbd.constructorArgumentLock) {
				//一個類裡面有多個構造函數,每個構造函數都有不同的參數,所以調用前需要根據參數鎖定要調用的構造函數或工廠方法
				if (mbd.resolvedConstructorOrFactoryMethod != null) {
					resolved = true;
					autowireNecessary = mbd.constructorArgumentsResolved;
				}
			}
		}
		//如果已經解析過則使用解析好的構造函數方法,不需要再次鎖定
		if (resolved) {
			if (autowireNecessary) {
				//構造函數自動註入
				return autowireConstructor(beanName, mbd, null, null);
			}
			else {
				//使用預設構造函數進行構造
				return instantiateBean(beanName, mbd);
			}
		}

		// Candidate constructors for autowiring?
		//需要根據參數解析構造函數
		Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
		if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
				mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
			//構造函數自動註入
			return autowireConstructor(beanName, mbd, ctors, args);
		}

		// Preferred constructors for default construction?
		// 預設構造的首選構造函數?
		ctors = mbd.getPreferredConstructors();
		if (ctors != null) {
			return autowireConstructor(beanName, mbd, ctors, null);
		}

		// No special handling: simply use no-arg constructor.
		//使用預設構造函數
		return instantiateBean(beanName, mbd);
	}

接下來分析以上幾點,算了不分析,太長了。我在另一篇文章Spring Ioc源碼分析系列--實例化Bean的幾種方法會填坑。這裡會詳細分析上面的幾點,好好把握,估計看到這都不知道啥跟啥了。

MergedBeanDefinitionPostProcessor的應用

到這裡我們已經實例化了一個bean對象,但是這個bean只是個半成品,空有外殼而無內在,所以接下來的工作就是對裡面的內容進行填充。那毫無疑問,按照Spring的尿性,肯定會在真正開始之前給你一個擴展點,讓你還要機會在屬性填充之前修改某些東西。我們經常使用的@Autowired註解就是在這裡實現的,後續會寫一篇Spring Ioc源碼分析系列--@Autowired註解的實現原理結合源碼和例子去分析它的實現。

跟進代碼查看,比較簡單,就是獲取所有的MergedBeanDefinitionPostProcessor,然後依次執行它的postProcessMergedBeanDefinition()方法。

	/**
	 * Apply MergedBeanDefinitionPostProcessors to the specified bean definition,
	 * invoking their {@code postProcessMergedBeanDefinition} methods.
	 *
	 * 將 MergedBeanDefinitionPostProcessors 應用於指定的 bean 定義,
	 * 調用它們的 {@code postProcessMergedBeanDefinition} 方法。
	 *
	 * 可以看到這個方法的代碼還是很簡單的,
	 * 就是調用了MergedBeanDefinitionPostProcessor的postProcessMergedBeanDefinition方法
	 *
	 * @param mbd the merged bean definition for the bean
	 * @param beanType the actual type of the managed bean instance
	 * @param beanName the name of the bean
	 * @see MergedBeanDefinitionPostProcessor#postProcessMergedBeanDefinition
	 */
	protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
		for (BeanPostProcessor bp : getBeanPostProcessors()) {
			if (bp instanceof MergedBeanDefinitionPostProcessor) {
				MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
				bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
			}
		}
	}
依賴處理

這部分主要是為了處理迴圈依賴而做的準備,這裡會根據earlySingletonExposure參數去判斷是否允許迴圈依賴,如果允許,則會調用addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean))方法將bean的早期引用放入到singletonFactories中。關於迴圈依賴的詳細處理過程,可以在下一篇文章Spring Ioc源碼分析系列--自動註入迴圈依賴的處理里看到。

		// Eagerly cache singletons to be able to resolve circular references
		// even when triggered by lifecycle interfaces like BeanFactoryAware.
		//是否需要提前暴露mbd.isSingleton() && this.allowCircularReferences &&
		//				isSingletonCurrentlyInCreation(beanName)
		boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
				isSingletonCurrentlyInCreation(beanName));
		if (earlySingletonExposure) {
			if (logger.isTraceEnabled()) {
				logger.trace("Eagerly caching bean '" + beanName +
						"' to allow for resolving potential circular references");
			}
			//為避免後期迴圈依賴,可以在bean初始化完成前將創建實例的ObjectFactory加入工廠
			//getEarlyBeanReference對bean再一次依賴引用,主要應用SmartInstantiationAwareBeanPostProcessor
			//其中我們熟悉的AOP就是在這裡將advice動態織入bean中,若沒有則直接返回bean,不做任何處理
			addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
		}

跟進addSingletonFactory()方法,可以看到這裡會先把早期引用放入到singletonFactories三級緩存中。

	/**
	 * Add the given singleton factory for building the specified singleton
	 * if necessary.
	 *
	 * 如有必要,添加給定的單例工廠以構建指定的單例。
	 *
	 * <p>To be called for eager registration of singletons, e.g. to be able to
	 * resolve circular references.
	 *
	 * 被提前註冊的單例Bean調用,例如用來解決迴圈依賴
	 *
	 * @param beanName the name of the bean
	 * @param singletonFactory the factory for the singleton object
	 */
	protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
		Assert.notNull(singletonFactory, "Singleton factory must not be null");
		synchronized (this.singletonObjects) {
			if (!this.singletonObjects.containsKey(beanName)) {
				this.singletonFactories.put(beanName, singletonFactory);
				this.earlySingletonObjects.remove(beanName);
				this.registeredSingletons.add(beanName);
			}
		}
	}

那放入到singletonFactories裡面的是什麼呢?從上面可以看到,這是一個lambada表達式,調用的方法的是getEarlyBeanReference(),跟進代碼查看。

	/**
	 * Obtain a reference for early access to the specified bean,
	 * typically for the purpose of resolving a circular reference.
	 *
	 * 獲取對指定 bean 的早期訪問的引用,通常用於解析迴圈引用。
	 *
	 * @param beanName the name of the bean (for error handling purposes)
	 * @param mbd the merged bean definition for the bean
	 * @param bean the raw bean instance
	 * @return the object to expose as bean reference
	 */
	protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
		Object exposedObject = bean;
		if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
			for (BeanPostProcessor bp : getBeanPostProcessors()) {
				if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
					SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
					// 對 bean 再一次依賴引用
					// 主要應用 SmartInstantiationAwareBeanPostProcessor, 
					// 其中我們熟知的 AOP 就是在這裡將 advice 動態織入 bean 中, 若沒有則直接返回 bean ,不做任何處理
					exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
				}
			}
		}
		return exposedObject;
	}
屬性填充

到這裡會已經完成了bean的實例化,早期引用的暴露,那接下來就到了屬性填充的部分,開始對bean進行各種賦值,讓一個空殼半成品bean完善成一個有血有肉的正常bean。

這裡可能存在依賴其他bean的屬性,則會遞歸初始化依賴bean。

populateBean() 函數中提供了這樣的處理流程。

  • InstantiationAwareBeanPostProcessor 處理器的 postProcessAfterinstantiation 函數的應用, 此函數可以控製程序是否繼續進行屬性填充。
  • 根據註入類型( byName/byType ),提取依賴的 bean,並統一存入 PropertyValues 中。
  • 應用 InstantiationAwareBeanPostProcessor 處理器的 postProcessPropertyValues 方法, 對屬性獲取完畢填充前對屬性的再次處理,典型應用是 RequiredAnnotationBeanPostProcessor 類中對屬性的驗證。
  • 將所有 PropertyValues 中的屬性填充至 BeanWrapper 中。

跟進代碼查看,又很長,這一塊的代碼真的是又臭又長。但是註釋很詳細,可以跟著看看。

	/**
	 * Populate the bean instance in the given BeanWrapper with the property values
	 * from the bean definition.
	 *
	 * 使用 bean 定義中的屬性值填充給定 BeanWrapper 中的 bean 實例。
	 *
	 * @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) {
			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;

		//給InstantiationAwareBeanPostProcessors最後一次機會在屬性設置前來改變 bean
		//如:可以用來支持屬性註入的類型
		// 滿足兩個條件,不是合成類 && 存在InstantiationAwareBeanPostProcessor
		// 其中InstantiationAwareBeanPostProcessor主要作用就是作為Bean的實例化前後的鉤子
		// 外加完成屬性註入,對於三個方法就是
		// postProcessBeforeInstantiation  創建對象前調用
		// postProcessAfterInstantiation   對象創建完成,@AutoWired註解解析後調用
		// postProcessPropertyValues(已過期,被postProcessProperties替代) 進行屬性註入
		// 下麵這段代碼的主要作用就是我們可以提供一個InstantiationAwareBeanPostProcessor
		// 提供的這個後置處理如果實現了postProcessAfterInstantiation方法並且返回false
		// 那麼可以跳過Spring預設的屬性註入,但是這也意味著我們要自己去實現屬性註入的邏輯
		// 所以一般情況下,我們也不會這麼去擴展
		if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
			for (BeanPostProcessor bp : getBeanPostProcessors()) {
				if (bp instanceof InstantiationAwareBeanPostProcessor) {
					InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
					//返回值為是否繼續填充bean
					if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
						continueWithPropertyPopulation = false;
						break;
					}
				}
			}
		}

		//如果後處理器發出停止填充命令則終止後續操作
		if (!continueWithPropertyPopulation) {
			return;
		}

		// 這裡其實就是判斷XML是否提供了屬性相關配置
		PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);

		// 確認註入模型
		int resolvedAutowireMode = mbd.getResolvedAutowireMode();

		// 主要處理byName跟byType兩種註入模型,byConstructor這種註入模型在創建對象的時候已經處理過了
		// 這裡都是對自動註入進行處理,byName跟byType兩種註入模型均是依賴setter方法
		// byName,根據setter方法的名字來查找對應的依賴,例如setA,那麼就是去容器中查找名字為a的Bean
		// byType,根據setter方法的參數類型來查找對應的依賴,例如setXx(A a),就是去容器中查詢類型為A的bean
		if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
			MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
			// Add property values based on autowire by name if applicable.
			if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
				//根據名稱註入
				autowireByName(beanName, mbd, bw, newPvs);
			}
			// Add property values based on autowire by type if applicable.
			if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
				//根據類型註入
				autowireByType(beanName, mbd, bw, newPvs);
			}
			// pvs是XML定義的屬性
			// 自動註入後,bean實際用到的屬性就應該要替換成自動註入後的屬性
			pvs = newPvs;
		}

		//後置處理器已經初始化
		// 檢查是否有InstantiationAwareBeanPostProcessor
		// 前面說過了,這個後置處理器就是來完成屬性註入的
		boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
		//需要依賴檢查
		//  是否需要依賴檢查,預設是不會進行依賴檢查的
		boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);

		// 下麵這段代碼有點麻煩了,因為涉及到版本問題
		// 其核心代碼就是調用了postProcessProperties完成了屬性註入
		PropertyDescriptor[] filteredPds = null;
		// 存在InstantiationAwareBeanPostProcessor,我們需要調用這類後置處理器的方法進行註入
		if (hasInstAwareBpps) {
			if (pvs == null) {
				pvs = mbd.getPropertyValues();
			}
			for (BeanPostProcessor bp : getBeanPostProcessors()) {
				if (bp instanceof InstantiationAwareBeanPostProcessor) {
					InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
					// 這句就是核心
					// Autowired 是通過 AutowiredAnnotationBeanPostProcessor#postProcessProperties() 實現的
					PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
					if (pvsToUse == null) {
						if (filteredPds == null) {
							// 得到需要進行依賴檢查的屬性的集合
							filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
						}
						//對所有需要依賴檢查的屬性做後置處理
						//  這個方法已經過時了,放到這裡就是為了相容老版本
						pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
						if (pvsToUse == null) {
							return;
						}
					}
					pvs = pvsToUse;
				}
			}
		}
		// 需要進行依賴檢查
		if (needsDepCheck) {
			if (filteredPds == null) {
				// 得到需要進行依賴檢查的屬性的集合
				filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
			}
			//依賴檢查,對應depends-on屬性,3.0已經棄用此屬性
			// 對需要進行依賴檢查的屬性進行依賴檢查
			checkDependencies(beanName, mbd, filteredPds, pvs);
		}

		// 將XML中的配置屬性應用到Bean上
		if (pvs != null) {
			//將屬性應用到bean中
			applyPropertyValues(beanName, mbd, bw, pvs);
		}
	}

這裡看到這裡會根據byName或者byType方式尋找依賴,然後調用applyPropertyValues()將屬性註入到BeanWrapperImpl里。

先來看autowireByName()方法,顧名思義,這裡會根據屬性名去獲取依賴。

	/**
	 * Fill in any missing property values with references to
	 * other beans in this factory if autowire is set to "byName".
	 * 
	 * 如果 autowire 設置為“byName”,則使用對該工廠中其他 bean 的引用填充任何缺少的屬性值。
	 * 
	 * @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) {

		//尋找bw中需要依賴註入的屬性值
		// 得到符合下麵條件的屬性名稱
		// 1.有setter方法
		// 2.需要進行依賴檢查
		// 3.不包含在XML配置中
		// 4.不是簡單類型(基本數據類型,枚舉,日期等)
		// 這裡可以看到XML配置優先順序高於自動註入的優先順序
		// 不進行依賴檢查的屬性,也不會進行屬性註入
		String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
		for (String propertyName : propertyNames) {
			if (containsBean(propertyName)) {
				//遞歸初始化相關bean
				Object bean = getBean(propertyName);
				// 將自動註入的屬性添加到pvs中去
				pvs.add(propertyName, bean);
				//註冊依賴
				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.
	 * 
	 * 定義“按類型自動裝配”(按類型的 bean 屬性)行為的抽象方法。 
	 * <p>這類似於 PicoContainer 預設值,其中 bean 工廠中必須只有一個屬性類型的 bean。
	 * 這使得 bean 工廠易於為小型命名空間配置,但不能像標準 Spring 行為那樣為大型應用程式工作。
	 * 
	 * @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) {

		// 這個類型轉換器,主要是在處理@Value時需要使用
		TypeConverter converter = getCustomTypeConverter();
		if (converter == null) {
			converter = bw;
		}

		Set<String> autowiredBeanNames = new LinkedHashSet<>(4);
		//尋找bw中需要依賴註入的屬性
		// 得到符合下麵條件的屬性名稱
		// 1.有setter方法
		// 2.需要進行依賴檢查
		// 3.不包含在XML配置中
		// 4.不是簡單類型(基本數據類型,枚舉,日期等)
		// 這裡可以看到XML配置優先順序高於自動註入的優先順序
		String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
		for (String propertyName : propertyNames) {
			try {
				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 類型按類型自動裝配:永遠沒有意義,即使它在技術上是一個不令人滿意的、不簡單的屬性。
				if (Object.class != pd.getPropertyType()) {
					//探測指定屬性的set方法
					// 這裡獲取到的就是setter方法的參數,因為我們需要按照類型進行註入嘛
					MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
					// Do not allow eager init for type matching in case of a prioritized post-processor.
					// 如果是PriorityOrdered在進行類型匹配時不會去匹配factoryBean
					// 如果不是PriorityOrdered,那麼在查找對應類型的依賴的時候會會去匹factoryBean
					// 這就是Spring的一種設計理念,實現了PriorityOrdered介面的Bean被認為是一種
					// 最高優先順序的 Bean,這一類的Bean在進行為了完成裝配而去檢查類型時,
					// 不去檢查 factoryBean
					// 具體可以參考PriorityOrdered介面上的註釋文檔
					boolean eager = !PriorityOrdered.class.isInstance(bw.getWrappedInstance());
					// 將參數封裝成為一個依賴描述符
					// 依賴描述符會通過:依賴所在的類,欄位名/方法名,依賴的具體類型等來描述這個依賴
					DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
					/**
					 * 解析指定beanName的屬性所匹配的值,並把解析到的屬性名存儲在autowiredBeanNames中,
					 * 當屬性存在多個封裝bean時,如:
					 * @Autowire
					 * private List<A> list;
					 * 將會找到所有匹配A類型的bean並將其註入
					 * 解析依賴,這裡會處理@Value註解
					 * 另外,通過指定的類型到容器中查找對應的bean
					 */
					Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
					if (autowiredArgument != null) {
						// 將查找出來的依賴屬性添加到pvs中,後面會將這個pvs應用到bean上
						pvs.add(propertyName, autowiredArgument);
					}
					// 註冊bean直接的依賴關係
					for (String autowiredBeanName : autowiredBeanNames) {
						//註冊依賴
						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);
			}
		}
	}

屬性依賴都獲取完了,接下來就是按部就班的進行註入了。

跟進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.
	 *
	 * 應用給定的屬性值,解析對此 bean 工廠中其他 bean 的任何運行時引用。必須使用深拷貝,所以我們不會永久修改這個屬性。
	 *
	 * @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) {
		if (pvs.isEmpty()) {
			return;
		}

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

		MutablePropertyValues mpvs = null;
		List<PropertyValue> original;

		if (pvs instanceof MutablePropertyValues) {
			mpvs = (MutablePropertyValues) pvs;
			if (mpvs.isConverted()) {
				// Shortcut: use the pre-converted values as-is.
				// 快捷方式:按原樣使用轉換前的值。
				try {
					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());
		}

		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();
				if (originalValue == AutowiredPropertyMarker.INSTANCE) {
					Method writeMethod = bw.getPropertyDescriptor(propertyName).getWriteMethod();
					if (writeMethod == null) {
						throw new IllegalArgumentException("Autowire marker for property without write method: " + pv);
					}
					originalValue = new DependencyDescriptor(new MethodParameter(writeMethod, 0), true);
				}
				// 給定一個 PropertyValue,返回一個值,必要時解析對工廠中其他 bean 的任何引用
				Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
				Object convertedValue = resolvedValue;
				boolean convertible = bw.isWritableProperty(propertyName) &&
						!PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
				if (convertible) {
					convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter);
				}
				// Possibly store converted value in merged bean definition,
				// in order to avoid re-conversion for every created bean instance.
				// 可能將轉換後的值存儲在合併的 bean 定義中,以避免對每個創建的 bean 實例進行重新轉換。
				if (resolvedValue == originalValue) {
					if (convertible) {
						pv.setConvertedValue(convertedValue);
					}
					deepCopy.add(pv);
				}
				else if (convertible && originalValue instanceof TypedStringValue &&
						!((TypedStringValue) originalValue).isDynamic() &&
						!(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) {
					pv.setConvertedValue(convertedValue);
					deepCopy.add(pv);
				}
				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);
		}
	}
調用初始化方法

初始化方法的調用邏輯在initializeBean(beanName, exposedObject, mbd)裡面,跟進代碼查看。

一看是不是很清晰,所以以後再遇到問你啥啥啥方法先執行,直接叼面試官。

	/**
	 *
	 * initializeBean()方法依次調用四個方法
	 * 1.invokeAwareMethods()
	 * 2.applyBeanPostProcessorsBeforeInitialization()
	 * 3.invokeInitMethods()
	 * 4.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 {
			// 1.先調用實現 aware 介面的方法
			invokeAwareMethods(beanName, bean);
		}

		Object wrappedBean = bean;
		if (mbd == null || !mbd.isSynthetic()) {
			// 2.調用 BeanPostProcessor#postProcessBeforeInitialization()方法
			wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
		}

		try {
			// 3.調用初始化方法,例如實現了 InitializingBean#afterPropertiesSet() 方法
			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()) {
			// 4.最後調用 BeanPostProcessor#postProcessAfterInitialization()
			wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
		}

		return wrappedBean;
	}
迴圈依賴檢查

這一步主要是實現一個兜底的檢測,避免出現註入了一個本該被代理的但是卻註入了一個原生bean的情況,這部分會在迴圈依賴的文章里結合來分析。

先看下代碼。

		if (earlySingletonExposure) {
			Object earlySingletonReference = getSingleton(beanName, false);
			//earlySingletonReference只有在檢測到迴圈依賴的情況下才不為空
			if (earlySingletonReference != null) {
				//如果exposedObject沒有在初始化方法中被改變,也就是沒有被增強
				if (exposedObject == bean) {
					exposedObject = earlySingletonReference;
				}
				else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
					String[] dependentBeans = getDependentBeans(beanName);
					Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
					//檢測依賴
					for (String dependentBean : dependentBeans) {
						if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
							actualDependentBeans.add(dependentBean);
						}
					}
					/**
					 * 因為bean創建完成後,其依賴的bean也一定是創建完成的
					 * 如果actualDependentBeans不為空,則說明依賴的bean還沒有被完全創建好
					 * 也就是說還存在迴圈依賴
					 */
					if (!actualDependentBeans.isEmpty()) {
						throw new BeanCurrentlyInCreationException(beanName,
								"Bean with name '" + beanName + "' has been injected into other beans [" +
								StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
								"] in its raw version as part of a circular reference, but has eventually been " +
								"wrapped. This means that said other beans do not use the final version of the " +
								"bean. This is often the result of over-eager type matching 

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 前臺部分到此結束,一路走來還挺懷念,今天主要是對整個項目的完成做一個最後的收尾工作,對於功能上的需求沒有什麼了,主要就是項目上線的一些註意事項。 一.個人中心二級路由 當我們點擊查看訂單應該跳轉到個人中心 個人中心拆分兩個子路由組件 分好組件後,在routes裡面父組件寫上childre配置項 寫路 ...
  • 前端周刊:2022-9 期 前端開發 網路視頻的防盜與破解 網路視頻(Web 視頻)是指利用 HTML5 技術在瀏覽器中播放的視頻,這類視頻資源通常可以被隨意下載,某些行業(比如教培行業)如果希望保護自己的視頻資源不被下載,就需要對視頻做防盜鏈處理。 Vue 組件復用問題的一個解決方法 關於 vue ...
  • 1. id選擇器 <style> #container { width: 100px; } </style> <body> <div id="container"></div> </body> 2. class選擇器 | 類選擇器 <style> .container { width: 100px; ...
  • Tooltip常用於展示滑鼠 hover 時的提示信息。 而在實際過程中,有這麼一個需求:只有文字內容排不下,出現省略號,才需要顯示tooltip的提示內容。 本文章的思路是通過一個自定義指令實現如下效果:姓名欄位過長時才顯示tooltip ...
  • 緊急通知!更新中.... (一)FastJson反序列化漏洞。據國家網路與信息安全信息通報中心監測發現,阿裡巴巴公司開源Java開發組件FastJson存在反序列化漏洞。FastJson被眾多java軟體作為組件集成,廣泛存在於java應用的服務端代碼中。攻擊者可利用上述漏洞實施任意文件寫入、服務端 ...
  • 摘要:NumPy中包含大量的函數,這些函數的設計初衷是能更方便地使用,掌握解這些函數,可以提升自己的工作效率。這些函數包括數組元素的選取和多項式運算等。下麵通過實例進行詳細瞭解。 前述通過對某公司股票的收盤價的分析,瞭解了某些Numpy的一些函數。通常實際中,某公司的股價被另外一家公司的股價緊緊跟隨 ...
  • 背景 框架之前完成了多數據源的動態切換及事務的處理,想更近一步提供一個簡單的跨庫事務處理功能,經過網上的搜索調研,大致有XA事務/SEGA事務/TCC事務等方案,因為業務主要涉及政府及企業且併發量不大,所以採用XA事務,雖然性能有所損失,但是可以保證數據的強一致性 方案設計 針對註冊的數據源拷貝一份 ...
  • 首先請記住一點,在電腦中所有的二進位都是以補碼的形式存儲的,所以你最後取反之後只是這個數的補碼,你還需要轉換成源碼,才是我們最終的十進位數字 下麵是計算過程: 正數取反(123,結果是-124): (1)先將此數變為二進位數,全部位取反(0變1,1變0); (2)由於這個數是補碼,所以要進行再一次 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...