spring bean初始化過程中的9個beanProcesser 后置處理器


BeanPostProcessor  是spring容器的容器的一個擴展點,可以進行自定義的實例化、初始化、依賴裝配、依賴檢查等流程,即可以覆蓋默認的實例化,也可以增強初始化、依賴注入、依賴檢查等流程。

Spring提供了很多BeanPostProcesser的擴展接口及其實現,用於完成除實例化之外的其他功能。

public interface BeanPostProcessor {
        
	@Nullable
	default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}

	
	@Nullable
	default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}    

  bean的創建和初始化

第1次調用后置處理器:

  

InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation

  第1次調用后置處理器在目標對象實例化之前調用,可以返回任意類型的值,如果不為空,此時可以代替原本應該生成的目標對象(一般是代理對象),並且會調用postProcessAfterInitialization 方法,否則走正常實例化流程

  源碼跟蹤:

    調用 AbstractAutowireCapableBeanFactory的createBean方法創建bean實例

  

protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
			throws BeanCreationException {

       。。。。。。。
    
     try {
			// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
			// 實例化前的后置處理器調用 InstantiationAwareBeanPostProcessor
			// 第1次調用后置處理器
			Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
			if (bean != null) {
				// 直接返回替代的對象實例,不再實例化目標對象
				return bean;
			}
		}

}

  AbstractAutowireCapableBeanFactory#resolveBeforeInstantiation 代碼如下

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.
			//確保此時bean類已經被解析
			if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
				Class<?> targetType = determineTargetType(beanName, mbd);
				if (targetType != null) {
					// 在目標對象實例化之前調用,可以返回任意類型的值,如果不為空,
					// 此時可以代替原本應該生成的目標對象實例(一般是代理對象)
					bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
					if (bean != null) {
						// 如果bean不為空,調用 postProcessAfterInitialization 方法,否則走正常實例化流程
						bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
					}
				}
			}
			mbd.beforeInstantiationResolved = (bean != null);
		}
		return bean;
	}


@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);
if (result != null) {
return result;
}
}
}
return null;
}

InstantiationAwareBeanPostProcessor 是BeanPostProcesser的子類,如果bean繼承了該類,則會走 applyBeanPostProcessorsBeforeInstantiation方法,不會走正常的實例化bean的流程,在此返回object對象

通過如上代碼可以進行實例化的預處理(自定義實例化bean,如創建相應的代理對象)和后處理(如 進行自定義實例化的bean的依賴裝配)。 

 

第2次調用后置處理器:

  第2次調用后置處理器,決定以哪種方式創建bean對象,(先通過工廠創建;如果不能,使用構造方法;最后使用無參構造 )假如類中有多個構造方法,生效的優先級(@Autowired > autowireMode =3  > 無參構造)

 

SmartInstantiationAwareBeanPostProcessor#determineCandidateConstructors

確定要為給定bean使用的候選構造器,檢查所有已注冊的構造器,實現類 AutowiredAnnotationBeanPostProcessor,掃描@Autowired修飾的構造器,判斷創建對象所用的構造 器(deafult,primary)

源碼跟蹤 :
    AbstractAutowireCapableBeanFactory的doCreateBean方法代碼如下:

	protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
			throws BeanCreationException {

         // Instantiate the bean.
		BeanWrapper instanceWrapper = null;
		if (mbd.isSingleton()) {
			instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
		}
		if (instanceWrapper == null) {
			/**
			 * 第2次調用后置處理器
			 * 創建bean實例,並將實例放在包裝類BeanWrapper中返回
			 * 1.通過工廠方法創建bean實例  method.invoke()
			 * 2.通過構造方法自動注入創建bean實例  clazz.newInstance()
			 * 3.通過無參構造器創建bean實例 clazz.newInstance()
 			 */
			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.
		synchronized (mbd.postProcessingLock) {
			if (!mbd.postProcessed) {
				try {
					//允許后置處理器修改合並的bean定義   MergedBeanDefinitionPostProcessor#postProcessMergedBeanDefinition
					// 第3次調用后置處理器
					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.
		// 急切地緩存單例,以便能夠解析循環引用,即使是由生命周期接口(如BeanFactoryAware)觸發的。
		// 如果當前是單例,且允許循環依賴而且當前bean處於創建狀態
		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");
			}
			// 添加到singletonFactories SmartInstantiationAwareBeanPostProcessor#getEarlyBeanReference
			//第4次調用后置處理器 提前暴露對象的引用到 singletonFactory 單例工廠中,解決循環引用的問題
			addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
		}

		// Initialize the bean instance.
		// 初始化bean實例
		Object exposedObject = bean;
		try {
			// 填充bean 設置屬性  InstantiationAwareBeanPostProcessors
			// 第5次,第6次調用后置處理器     注入依賴
			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) {
			Object earlySingletonReference = getSingleton(beanName, false);
			if (earlySingletonReference != null) {
				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);
						}
					}
					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 {
			// 將bean注冊為可以銷毀   DestructionAwareBeanPostProcessor bean的銷毀后置處理器
			// 第九次調用后置處理器
			registerDisposableBeanIfNecessary(beanName, bean, mbd);
		}
		catch (BeanDefinitionValidationException ex) {
			throw new BeanCreationException(
					mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
		}

		return exposedObject;




}

  

AbstractAutowireCapableBeanFactory.createBeanInstance()

protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {

      ..........
     // Candidate constructors for autowiring?
		// 自動裝配的候選構造器   SmartInstantiationAwareBeanPostProcessor#determineCandidateConstructors
		// 第2次調用后置處理器
		Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
		//  AutowireMode設置為3,采用構造器貪婪模式  最多參數構造器注入    Autowire)constructor = 3
		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);

}    

  

第3次調用后置處理器:見上面代碼:

    

MergedBeanDefinitionPostProcessor#postProcessMergedBeanDefinition

 

  允許后置處理器修改合並的bean定義 ,實現類 AutowiredAnnotationBeanPostProcessor,用於掃描 @Autowired和@Value修飾的屬性和方法,封裝到InjectionMetadata。  

  AutowiredAnnotationBeanPostProcessor 將掃描 Spring 容器中所有 Bean,當發現 Bean 中擁有@Autowired 注解時就找到和其匹配(默認按類型匹配)的 Bean,並注入到對應的地方中去。會調用到AutowiredAnnotationBeanPostProcessor 的buildAutowiringMetadata()方法,buildAutowiringMetadata方法解析等待自動注入類的所有屬性。它通過分析所有字段和方法並初始化org.springframework.beans.factory.annotation.InjectionMetadata類的實例來實現。
詳細代碼如下:
private InjectionMetadata buildAutowiringMetadata(final Class<?> clazz) {
		List<InjectionMetadata.InjectedElement> elements = new ArrayList<>();
		Class<?> targetClass = clazz;

		do {
			final List<InjectionMetadata.InjectedElement> currElements = new ArrayList<>();

			ReflectionUtils.doWithLocalFields(targetClass, field -> {
// 找到@Autowired 注解修飾的屬性, AnnotationAttributes ann = findAutowiredAnnotation(field); if (ann != null) { if (Modifier.isStatic(field.getModifiers())) { if (logger.isInfoEnabled()) { logger.info("Autowired annotation is not supported on static fields: " + field); } return; } boolean required = determineRequiredStatus(ann); currElements.add(new AutowiredFieldElement(field, required)); } }); ReflectionUtils.doWithLocalMethods(targetClass, method -> { Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method); if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) { return; }// 找到@Autowired 修飾的方法 AnnotationAttributes ann = findAutowiredAnnotation(bridgedMethod); if (ann != null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) { if (Modifier.isStatic(method.getModifiers())) { if (logger.isInfoEnabled()) { logger.info("Autowired annotation is not supported on static methods: " + method); } return; } if (method.getParameterCount() == 0) { if (logger.isInfoEnabled()) { logger.info("Autowired annotation should only be used on methods with parameters: " + method); } } boolean required = determineRequiredStatus(ann); PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz); currElements.add(new AutowiredMethodElement(method, required, pd)); } }); elements.addAll(0, currElements); targetClass = targetClass.getSuperclass(); } while (targetClass != null && targetClass != Object.class);           // 生成一個 InjectionMetadata對象,進行屬性賦值(通過反射) return new InjectionMetadata(clazz, elements); }

  

 

  第4次調用后置處理器:解決循環引用的問題,提前暴露對象的應用到 SingletonFactory 單例工廠中,此時對象的屬性未賦值;詳細見spring循環依賴;

  第5次調用后置處理器:

       

InstantiationAwareBeanPostProcessor#postProcessAfterInstantiation

 

  在目標對象實例化之后調用,此時對象被實例化,但是對象的屬性還未被設置。如果該方法返回false,則會忽略之后的屬性設置;返回true,則進行正常的屬性設置。

源碼跟蹤:

  

// 初始化bean實例
		Object exposedObject = bean;
		try {
			// 填充bean 設置屬性  InstantiationAwareBeanPostProcessors
			// 第5次,第6次調用后置處理器     注入依賴
			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);
			}
		}

  

	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;
		//  在屬性設置之前修改bean的狀態  InstantiationAwareBeanPostProcessor#postProcessAfterInstantiation
		// 第5次調用后置處理器
		if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
			for (BeanPostProcessor bp : getBeanPostProcessors()) {
				if (bp instanceof InstantiationAwareBeanPostProcessor) {
					InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
					//在目標對象實例化之后調用,此時對象被實例化,但是對象的屬性還未設置。如果該方法返回
					//fasle,則會忽略之后的屬性設置。返回true,按正常流程設置屬性值
					if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
						continueWithPropertyPopulation = false;
						break;
					}
				}
			}
		}

		if (!continueWithPropertyPopulation) {
			// InstantiationAwareBeanPostProcessor#postProcessAfterInstantiation方法返回false,
			// 直接返回,將忽略實例的屬性設置
			return;
		}

		PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);

		// 判斷autowireMode否是 by_name或者by_type
		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 = newPvs;
		}

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

		PropertyDescriptor[] filteredPds = null;
		if (hasInstAwareBpps) {
			if (pvs == null) {
				pvs = mbd.getPropertyValues();
			}
			//InstantiationAwareBeanPostProcessor.postProcessProperties
			// 第6次調用后置處理器
			// 可以在該方法內對屬性值進行修改(此時屬性值還未設置,但可以修改原本會設置的進去的屬性值)。
			// 如果postProcessAfterInstantiation方法返回false,該方法不會調用
			for (BeanPostProcessor bp : getBeanPostProcessors()) {
				if (bp instanceof InstantiationAwareBeanPostProcessor) {

					//處理 @Autowired 屬性注入邏輯
					// AutowiredAnnotationBeanPostProcessor.postProcessProperties
					//InjectionMetadata#inject
					//AutowiredAnnotationBeanPostProcessor.AutowiredFieldElement#inject
					//DefaultListableBeanFactory#resolveDependency
					//DefaultListableBeanFactory#doResolveDependency
					//DependencyDescriptor#resolveCandidate //此方法直接返回 beanFactory.getBean(beanName);

					InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
					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);
			}
			checkDependencies(beanName, mbd, filteredPds, pvs);
		}

		if (pvs != null) {
			// 普通屬性填充   propertyValues
			applyPropertyValues(beanName, mbd, bw, pvs);
		}
	}

  

  第6次調用后置處理器,用來處理Bean中 屬性注入,包括 @Autowired 注入;此時如果存在循環引用的問題,也會一並處理掉(從單例工廠中獲取屬性bean,生成earlySingletonObject,添加到earlySingletonObjects中,解決循環依賴問題);(代碼見上)

  第7次調用后置處理器:  主要用於處理aware接口,bean.setXXXAware()

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 {

			invokeAwareMethods(beanName, bean);
		}

 		Object wrappedBean = bean;
		if (mbd == null || !mbd.isSynthetic()) {
			//  BeanPostProcessor.postProcessBeforeInitialization
			//第7次調用后置處理器
			//  如果配置了@PostConstruct  會調用
			// InitDestroyAnnotationBeanPostProcessor#postProcessBeforeInitialization
			wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
		}

		try {
			// 執行bean生命周期回調的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()) {
			//  BeanPostProcessor.postProcessAfterInitialization
			//第8次調用后置處理器
			//   aop實現:AbstractAutoProxyCreator#postProcessAfterInitialization
			wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
		}

		return wrappedBean;
	}

  

BeanPostProcessor#postProcessBeforeInitialization

  在bean new出來並完成屬性填充之后,回調init方法之前調用;

  其他擴展:處理aware方法調用,比如實現了ApplicationContextAware或者EnvironmentAware接口,

ApplicationContextAwareProcessor#postProcessBeforeInitialization

  

如果配置了@PostConstruct 會調用     

InitDestroyAnnotationBeanPostProcessor#postProcessBeforeInitialization

  說明 :構造方法 > @Autowired > @PostContruct 方法 執行順序 (此時還未執行bean的 init 初始化方法),@PostContruct 修飾的方法,主要用於bean實例化 屬性注入之后的調用

源碼追蹤:

AbstractAutowireCapableBeanFactory#initializeBean(String, Object, RootBeanDefinition) 
> wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName)

  

  第8次調用后置處理器:在執行bean的 init方法之后調用;擴展:spring的aop基於此實現;源碼見 上

  第9次調用后置處理器:標記單例bean為可銷毀的,

AbstractBeanFactory  

    protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
		AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
		//requiresDestruction中調用DestructionAwareBeanPostProcessor#requiresDestruction
		//第九次調用后置處理器  確定給定的bean實例是否需要銷毀后處理器  單例bean才會加標記 為可銷毀,
// (這里是registerDisposableBean方法加入到 DefaultSingletonBeanFactory 中的 disposableBeans 中,是個map,k-beanName,v-bean) if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) { if (mbd.isSingleton()) { // Register a DisposableBean implementation that performs all destruction // work for the given bean: DestructionAwareBeanPostProcessors, // DisposableBean interface, custom destroy method. registerDisposableBean(beanName, new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc)); } else { // A bean with a custom scope... Scope scope = this.scopes.get(mbd.getScope()); if (scope == null) { throw new IllegalStateException("No Scope registered for scope name '" + mbd.getScope() + "'"); } scope.registerDestructionCallback(beanName, new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc)); } } }

  

 

    

 

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM