Spring的IOC容器初始化源碼分析三:refresh(03)

11.finishBeanFactoryInitialization
finishBeanFactoryInitialization方法做了兩件事:
 1.beanFactory對象的初始化;
 2.bean配置文件中配置的那些單例的bean,都是在finishBeanFactoryInitialization方法中實例化的;
 //對配置了lazy-init屬性的Bean進行預實例化處理
	protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
		// Initialize conversion service for this context.
		//這是Spring3以後新加的代碼,爲容器指定一個轉換服務(ConversionService)
		//在對某些Bean屬性進行轉換時使用
		// 實例化類型轉換的bean,並保存在ApplicationContext中
		if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
				beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
			beanFactory.setConversionService(
					beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
		}

		// Register a default embedded value resolver if no bean post-processor
		// (such as a PropertyPlaceholderConfigurer bean) registered any before:
		// at this point, primarily for resolution in annotation attribute values.
		if (!beanFactory.hasEmbeddedValueResolver()) {
			beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
		}

		// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
		// 實例化LoadTimeWeaverAware接口的bean,用於ApsectJ的類加載期織入的處理
		String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
		for (String weaverAwareName : weaverAwareNames) {
			getBean(weaverAwareName);
		}

		// Stop using the temporary ClassLoader for type matching.
		//爲了類型匹配,停止使用臨時的類加載器
		// 確保臨時的classLoader爲空,臨時classLoader一般被用來做類型匹配的
		beanFactory.setTempClassLoader(null);

		// Allow for caching all bean definition metadata, not expecting further changes.
		//緩存容器中所有註冊的BeanDefinition元數據,以防被修改
		// 將一個標誌設置爲true,表示applicationContext已經緩存了所有bean的定義,這些bean的name都被保存在applicationContext的frozenBeanDefinitionNames成員變量中,相當於一個快照,記錄了當前那些bean的定義已經拿到了
		
		beanFactory.freezeConfiguration();

		// Instantiate all remaining (non-lazy-init) singletons.
		//對配置了lazy-init屬性的單態模式Bean進行預實例化處理
		beanFactory.preInstantiateSingletons();
	}

	preInstantiateSingletons
	
	public void preInstantiateSingletons() throws BeansException {
		if (this.logger.isDebugEnabled()) {
			this.logger.debug("Pre-instantiating singletons in " + this);
		}

		// Iterate over a copy to allow for init methods which in turn register new bean definitions.
		// While this may not be part of the regular factory bootstrap, it does otherwise work fine.
		List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);

		// Trigger initialization of all non-lazy singleton beans...
		for (String beanName : beanNames) {
			//獲取指定名稱的Bean定義,該定義已經和父類定義做了合併
			RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
			//Bean不是抽象的,是單態模式的,且lazy-init屬性配置爲false
			if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
				//如果指定名稱的bean是創建容器的Bean
				if (isFactoryBean(beanName)) {
					//FACTORY_BEAN_PREFIX=”&”,當Bean名稱前面加”&”符號
					//時,獲取的是產生容器對象本身,而不是容器產生的Bean.
					//調用getBean方法,觸發容器對Bean實例化和依賴注入過程
					final FactoryBean<?> factory = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
					//標識是否需要預實例化
					boolean isEagerInit;
					if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
						//一個匿名內部類
						isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>) () ->
								((SmartFactoryBean<?>) factory).isEagerInit(),
								getAccessControlContext());
					}
					else {
						isEagerInit = (factory instanceof SmartFactoryBean &&
								((SmartFactoryBean<?>) factory).isEagerInit());
					}
					if (isEagerInit) {
						//調用getBean方法,觸發容器對Bean實例化和依賴注入過程
						getBean(beanName);
					}
				}
				else {
					getBean(beanName);
				}
			}
		}

		// Trigger post-initialization callback for all applicable beans...
		for (String beanName : beanNames) {
			Object singletonInstance = getSingleton(beanName);
			if (singletonInstance instanceof SmartInitializingSingleton) {
				final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
				if (System.getSecurityManager() != null) {
					AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
						smartSingleton.afterSingletonsInstantiated();
						return null;
					}, getAccessControlContext());
				}
				else {
					smartSingleton.afterSingletonsInstantiated();
				}
			}
		}
	}


	//獲取IOC容器中指定名稱的Bean
	@Override
	public Object getBean(String name) throws BeansException {
		//doGetBean纔是真正向IoC容器獲取被管理Bean的過程
		return doGetBean(name, null, null, false);
	}

	//真正實現向IOC容器獲取Bean的功能,也是觸發依賴注入功能的地方
	protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
			@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {

		//根據指定的名稱獲取被管理Bean的名稱,剝離指定名稱中對容器的相關依賴
		//如果指定的是別名,將別名轉換爲規範的Bean名稱
		final String beanName = transformedBeanName(name);
		Object bean;

		// Eagerly check singleton cache for manually registered singletons.
		//先從緩存中取是否已經有被創建過的單態類型的Bean
		//對於單例模式的Bean整個IOC容器中只創建一次,不需要重複創建
		Object sharedInstance = getSingleton(beanName);
		//IOC容器創建單例模式Bean實例對象
		if (sharedInstance != null && args == null) {
			if (logger.isDebugEnabled()) {
				//如果指定名稱的Bean在容器中已有單例模式的Bean被創建
				//直接返回已經創建的Bean
				if (isSingletonCurrentlyInCreation(beanName)) {
					logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +
							"' that is not fully initialized yet - a consequence of a circular reference");
				}
				else {
					logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
				}
			}
			//獲取給定Bean的實例對象,主要是完成FactoryBean的相關處理
			//注意:BeanFactory是管理容器中Bean的工廠,而FactoryBean是
			//創建創建對象的工廠Bean,兩者之間有區別
			bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
		}

		else {
			// Fail if we're already creating this bean instance:
			// We're assumably within a circular reference.
			//緩存沒有正在創建的單例模式Bean
			//緩存中已經有已經創建的原型模式Bean
			//但是由於循環引用的問題導致實例化對象失敗
			if (isPrototypeCurrentlyInCreation(beanName)) {
				throw new BeanCurrentlyInCreationException(beanName);
			}

			// Check if bean definition exists in this factory.
			//對IOC容器中是否存在指定名稱的BeanDefinition進行檢查,首先檢查是否
			//能在當前的BeanFactory中獲取的所需要的Bean,如果不能則委託當前容器
			//的父級容器去查找,如果還是找不到則沿着容器的繼承體系向父級容器查找
			BeanFactory parentBeanFactory = getParentBeanFactory();
			//當前容器的父級容器存在,且當前容器中不存在指定名稱的Bean
			if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
				// Not found -> check parent.
				//解析指定Bean名稱的原始名稱
				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 {
					// No args -> delegate to standard getBean method.
					//委派父級容器根據指定名稱和類型查找
					return parentBeanFactory.getBean(nameToLookup, requiredType);
				}
			}

			//創建的Bean是否需要進行類型驗證,一般不需要
			if (!typeCheckOnly) {
				//向容器標記指定的Bean已經被創建
				markBeanAsCreated(beanName);
			}

			try {
				//根據指定Bean名稱獲取其父級的Bean定義
				//主要解決Bean繼承時子類合併父類公共屬性問題
				final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
				checkMergedBeanDefinition(mbd, beanName, args);

				// Guarantee initialization of beans that the current bean depends on.
				//獲取當前Bean所有依賴Bean的名稱
				String[] dependsOn = mbd.getDependsOn();
				//如果當前Bean有依賴Bean
				if (dependsOn != null) {
					for (String dep : dependsOn) {
						if (isDependent(beanName, dep)) {
							throw new BeanCreationException(mbd.getResourceDescription(), beanName,
									"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
						}
						//遞歸調用getBean方法,獲取當前Bean的依賴Bean
						registerDependentBean(dep, beanName);
						//把被依賴Bean註冊給當前依賴的Bean
						getBean(dep);
					}
				}

				// Create bean instance.
				//創建單例模式Bean的實例對象
				if (mbd.isSingleton()) {
					//這裏使用了一個匿名內部類,創建Bean實例對象,並且註冊給所依賴的對象
					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.
							//顯式地從容器單例模式Bean緩存中清除實例對象
							destroySingleton(beanName);
							throw ex;
						}
					});
					//獲取給定Bean的實例對象
					bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
				}

				//IOC容器創建原型模式Bean實例對象
				else if (mbd.isPrototype()) {
					// It's a prototype -> create a new instance.
					//原型模式(Prototype)是每次都會創建一個新的對象
					Object prototypeInstance = null;
					try {
						//回調beforePrototypeCreation方法,默認的功能是註冊當前創建的原型對象
						beforePrototypeCreation(beanName);
						//創建指定Bean對象實例
						prototypeInstance = createBean(beanName, mbd, args);
					}
					finally {
						//回調afterPrototypeCreation方法,默認的功能告訴IOC容器指定Bean的原型對象不再創建
						afterPrototypeCreation(beanName);
					}
					//獲取給定Bean的實例對象
					bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
				}

				//要創建的Bean既不是單例模式,也不是原型模式,則根據Bean定義資源中
				//配置的生命週期範圍,選擇實例化Bean的合適方法,這種在Web應用程序中
				//比較常用,如:request、session、application等生命週期
				else {
					String scopeName = mbd.getScope();
					final Scope scope = this.scopes.get(scopeName);
					//Bean定義資源中沒有配置生命週期範圍,則Bean定義不合法
					if (scope == null) {
						throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
					}
					try {
						//這裏又使用了一個匿名內部類,獲取一個指定生命週期範圍的實例
						Object scopedInstance = scope.get(beanName, () -> {
							beforePrototypeCreation(beanName);
							try {
								return createBean(beanName, mbd, args);
							}
							finally {
								afterPrototypeCreation(beanName);
							}
						});
						//獲取給定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.isDebugEnabled()) {
					logger.debug("Failed to convert bean '" + name + "' to required type '" +
							ClassUtils.getQualifiedName(requiredType) + "'", ex);
				}
				throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
			}
		}
		return (T) bean;
	}

	//創建Bean實例對象
	@Override
	protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
			throws BeanCreationException {

		if (logger.isDebugEnabled()) {
			logger.debug("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.
		//判斷需要創建的Bean是否可以實例化,即是否可以通過當前的類加載器加載
		Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
		if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
			mbdToUse = new RootBeanDefinition(mbd);
			mbdToUse.setBeanClass(resolvedClass);
		}

		// Prepare method overrides.
		//校驗和準備Bean中的方法覆蓋
		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.
			//如果Bean配置了初始化前和初始化後的處理器,則試圖返回一個需要創建Bean的代理對象
			Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
			if (bean != null) {
				return bean;
			}
		}
		catch (Throwable ex) {
			throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
					"BeanPostProcessor before instantiation of bean failed", ex);
		}

		try {
			//創建Bean的入口
			Object beanInstance = doCreateBean(beanName, mbdToUse, args);
			if (logger.isDebugEnabled()) {
				logger.debug("Finished creating instance of bean '" + beanName + "'");
			}
			return beanInstance;
		}
		catch (BeanCreationException ex) {
			// A previously detected exception with proper bean creation context already...
			throw ex;
		}
		catch (ImplicitlyAppearedSingletonException ex) {
			// An IllegalStateException to be communicated up to DefaultSingletonBeanRegistry...
			throw ex;
		}
		catch (Throwable ex) {
			throw new BeanCreationException(
					mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
		}
	}
//真正創建Bean的方法
	protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
			throws BeanCreationException {

		// Instantiate the bean.
		//封裝被創建的Bean對象
		BeanWrapper instanceWrapper = null;
		if (mbd.isSingleton()) {
			instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
		}
		if (instanceWrapper == null) {
			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.
		//調用PostProcessor後置處理器
		synchronized (mbd.postProcessingLock) {
			if (!mbd.postProcessed) {
				try {
					applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
				}
				catch (Throwable ex) {
					throw new BeanCreationException(mbd.getResourceDescription(), beanName,
							"Post-processing of merged bean definition failed", ex);
				}
				mbd.postProcessed = true;
			}
		}

		// Eagerly cache singletons to be able to resolve circular references
		// even when triggered by lifecycle interfaces like BeanFactoryAware.
		//向容器中緩存單例模式的Bean對象,以防循環引用
		boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
				isSingletonCurrentlyInCreation(beanName));
		if (earlySingletonExposure) {
			if (logger.isDebugEnabled()) {
				logger.debug("Eagerly caching bean '" + beanName +
						"' to allow for resolving potential circular references");
			}
			//這裏是一個匿名內部類,爲了防止循環引用,儘早持有對象的引用
			addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
		}

		// Initialize the bean instance.
		//Bean對象的初始化,依賴注入在此觸發
		//這個exposedObject在初始化完成之後返回作爲依賴注入完成後的Bean
		Object exposedObject = bean;
		try {
			//將Bean實例對象封裝,並且Bean定義中配置的屬性值賦值給實例對象
			populateBean(beanName, mbd, instanceWrapper);
			//初始化Bean對象
			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) {
			//獲取指定名稱的已註冊的單例模式Bean對象
			Object earlySingletonReference = getSingleton(beanName, false);
			if (earlySingletonReference != null) {
				//根據名稱獲取的已註冊的Bean和正在實例化的Bean是同一個
				if (exposedObject == bean) {
					//當前實例化的Bean初始化完成
					exposedObject = earlySingletonReference;
				}
				//當前Bean依賴其他Bean,並且當發生循環引用時不允許新創建實例對象
				else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
					String[] dependentBeans = getDependentBeans(beanName);
					Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
					//獲取當前Bean所依賴的其他Bean
					for (String dependentBean : dependentBeans) {
						//對依賴Bean進行類型檢查
						if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
							actualDependentBeans.add(dependentBean);
						}
					}
					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.
		//註冊完成依賴注入的Bean
		try {
			registerDisposableBeanIfNecessary(beanName, bean, mbd);
		}
		catch (BeanDefinitionValidationException ex) {
			throw new BeanCreationException(
					mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
		}

		return exposedObject;
	}
	
	//將Bean屬性設置到生成的實例對象上
	
	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;

		if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
			for (BeanPostProcessor bp : getBeanPostProcessors()) {
				if (bp instanceof InstantiationAwareBeanPostProcessor) {
					InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
					if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
						continueWithPropertyPopulation = false;
						break;
					}
				}
			}
		}

		if (!continueWithPropertyPopulation) {
			return;
		}
		//獲取容器在解析Bean定義資源時爲BeanDefiniton中設置的屬性值
		PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);

		//對依賴注入處理,首先處理autowiring自動裝配的依賴注入
		if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
				mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
			MutablePropertyValues newPvs = new MutablePropertyValues(pvs);

			// Add property values based on autowire by name if applicable.
			//根據Bean名稱進行autowiring自動裝配處理
			if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
				autowireByName(beanName, mbd, bw, newPvs);
			}

			// Add property values based on autowire by type if applicable.
			//根據Bean類型進行autowiring自動裝配處理
			if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
				autowireByType(beanName, mbd, bw, newPvs);
			}

			pvs = newPvs;
		}

		//對非autowiring的屬性進行依賴注入處理

		boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
		boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);

		if (hasInstAwareBpps || needsDepCheck) {
			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;
						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);
		}
	}

	initializeBean
	//初始容器創建的Bean實例對象,爲其添加BeanPostProcessor後置處理器
	protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
		//JDK的安全機制驗證權限
		if (System.getSecurityManager() != null) {
			//實現PrivilegedAction接口的匿名內部類
			AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
				invokeAwareMethods(beanName, bean);
				return null;
			}, getAccessControlContext());
		}
		else {
			//爲Bean實例對象包裝相關屬性,如名稱,類加載器,所屬容器等信息
			invokeAwareMethods(beanName, bean);
		}

		Object wrappedBean = bean;
		//對BeanPostProcessor後置處理器的postProcessBeforeInitialization
		//回調方法的調用,爲Bean實例初始化前做一些處理
		if (mbd == null || !mbd.isSynthetic()) {
			wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
		}

		//調用Bean實例對象初始化的方法,這個初始化方法是在Spring Bean定義配置
		//文件中通過init-method屬性指定的
		try {
			invokeInitMethods(beanName, wrappedBean, mbd);
		}
		catch (Throwable ex) {
			throw new BeanCreationException(
					(mbd != null ? mbd.getResourceDescription() : null),
					beanName, "Invocation of init method failed", ex);
		}
		//對BeanPostProcessor後置處理器的postProcessAfterInitialization
		//回調方法的調用,爲Bean實例初始化之後做一些處理
		if (mbd == null || !mbd.isSynthetic()) {
			wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
		}

		return wrappedBean;
	}
	
	
	private void invokeAwareMethods(final String beanName, final Object bean) {
		if (bean instanceof Aware) {
			if (bean instanceof BeanNameAware) {
				((BeanNameAware) bean).setBeanName(beanName);
			}
			if (bean instanceof BeanClassLoaderAware) {
				ClassLoader bcl = getBeanClassLoader();
				if (bcl != null) {
					((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
				}
			}
			if (bean instanceof BeanFactoryAware) {
				((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
			}
		}
	}
	
	
	
	protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
			throws Throwable {

		boolean isInitializingBean = (bean instanceof InitializingBean);
		if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
			if (logger.isDebugEnabled()) {
				logger.debug("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
			}
			if (System.getSecurityManager() != null) {
				try {
					AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
						((InitializingBean) bean).afterPropertiesSet();
						return null;
					}, getAccessControlContext());
				}
				catch (PrivilegedActionException pae) {
					throw pae.getException();
				}
			}
			else {
				((InitializingBean) bean).afterPropertiesSet();
			}
		}

		if (mbd != null && bean.getClass() != NullBean.class) {
			String initMethodName = mbd.getInitMethodName();
			if (StringUtils.hasLength(initMethodName) &&
					!(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
					!mbd.isExternallyManagedInitMethod(initMethodName)) {
				invokeCustomInitMethod(beanName, bean, mbd);
			}
		}
	}

	
	
12.finishRefresh
	protected void finishRefresh() {
		// Clear context-level resource caches (such as ASM metadata from scanning).
		
		clearResourceCaches();

		// Initialize lifecycle processor for this context.
		// 檢查是否已經配置了生命週期處理器,如果沒有就new一個DefaultLifecycleProcessor
		initLifecycleProcessor();

		// Propagate refresh to lifecycle processor first.
		// 找到所有實現了Lifecycle接口的bean,按照每個bean設置的生命週期階段進行分組,再依次調用每個分組中每個bean的start方法,完成生命週期監聽的通知
		getLifecycleProcessor().onRefresh();

		// Publish the final event.
		// 創建一條代表applicationContext刷新完成的事件,交給廣播器去廣播
		publishEvent(new ContextRefreshedEvent(this));

		// Participate in LiveBeansView MBean, if active.
		// 如果配置了MBeanServer,就完成在MBeanServer上的註冊
		LiveBeansView.registerApplicationContext(this);
	}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章