spring 笔记5 bean的生命周期,BeanPostProcessor

BeanPostProcessor接口

public interface BeanPostProcessor {
    Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;//初始化
	Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;
}

	public interface DestructionAwareBeanPostProcessor extends BeanPostProcessor {
	   void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException;//毁掉
	}

    public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor {
	   Object postProcessBeforeInstantiation(Class beanClass, String beanName) throws BeansException;//实例化
	   boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException;
	   PropertyValues postProcessPropertyValues(
			PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName)
			throws BeansException;
	}
	     public interface SmartInstantiationAwareBeanPostProcessor extends InstantiationAwareBeanPostProcessor {
		      Class predictBeanType(Class beanClass, String beanName) throws BeansException;
			  Constructor[] determineCandidateConstructors(Class beanClass, String beanName) throws BeansException;
			  Object getEarlyBeanReference(Object bean, String beanName) throws BeansException;
		 }
	
	
	public interface MergedBeanDefinitionPostProcessor extends BeanPostProcessor {
	   void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class beanType, String beanName);
    }

//方法1

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

		if (logger.isDebugEnabled()) {
			logger.debug("Creating instance of bean '" + beanName + "'");
		}
		// Make sure bean class is actually resolved at this point.
		resolveBeanClass(mbd, beanName);

		// Prepare method overrides.
		try {
			mbd.prepareMethodOverrides();
		}
		catch (BeanDefinitionValidationException ex) {
			throw new BeanDefinitionStoreException(mbd.getResourceDescription(),
					beanName, "Validation of method overrides failed", ex);
		}

		try {
			/*/1 Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
			//给BeanPostProcessors一个机会返回一个代理类替代目标对象?
			Object bean = resolveBeforeInstantiation(beanName, mbd);
			if (bean != null) {
				return bean;
			}
		}
		catch (Throwable ex) {
			throw new BeanCreationException(mbd.getResourceDescription(), beanName,
					"BeanPostProcessor before instantiation of bean failed", ex);
		}

		Object beanInstance = doCreateBean(beanName, mbd, args);
		if (logger.isDebugEnabled()) {
			logger.debug("Finished creating instance of bean '" + beanName + "'");
		}
		return beanInstance;
	}
注释
/*/1
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.hasBeanClass() && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
				bean = applyBeanPostProcessorsBeforeInstantiation(mbd.getBeanClass(), beanName);
				//取工厂中的InstantiationAwareBeanPostProcessor执行postProcessBeforeInstantiation方法
				//不少实现类此方法都是返回null ?
				if (bean != null) {
					bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
					//取工厂中所有的BeanPostProcessor 执行postProcessAfterInitialization方法
				}
			}
			mbd.beforeInstantiationResolved = (bean != null);
		}
		return bean;
	}
	

//方法2


protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) {
		// Instantiate the bean.
		....
			instanceWrapper = createBeanInstance(beanName, mbd, args);
			//createBeanInstance{
			//       Constructor[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
			//         //取工厂中的SmartInstantiationAwareBeanPostProcessor 执行determineCandidateConstructors得到Constructor[]
			//
			//
			//
			//
			//         autowireConstructor();
			//         instantiateBean(){;//无参的构造方法
			//              beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
			//                //getInstantiationStrategy() = CglibSubclassingInstantiationStrategy()
			//                //constructorToUse = clazz.getDeclaredConstructor((Class[]) null);
			//                //beanDefinition.resolvedConstructorOrFactoryMethod = constructorToUse;
			//                //return BeanUtils.instantiateClass(constructorToUse);(实现使用方法ctor.newInstance(args);)
			//         }
			//}
		....
		
		// Allow post-processors to modify the merged bean definition.
		synchronized (mbd.postProcessingLock) {
			if (!mbd.postProcessed) {
				applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
				//
				//取工厂中所有的MergedBeanDefinitionPostProcessor执行postProcessMergedBeanDefinition方法
				//
				//
				//
				mbd.postProcessed = true;
			}
		}

		// Eagerly cache singletons to be able to resolve circular references
		// even when triggered by lifecycle interfaces like BeanFactoryAware.
		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, new ObjectFactory() {
				public Object getObject() throws BeansException {
					return getEarlyBeanReference(beanName, mbd, bean);
					//
					//取工厂中所有的SmartInstantiationAwareBeanPostProcessor执行getEarlyBeanReference返回
					//
					//
					//
				}
			});
		}

		// Initialize the bean instance.实例化
		Object exposedObject = bean;
		try {
			populateBean(beanName, mbd, instanceWrapper);//把从definnation装好property的实例装进wrapper
			//实例化前
			//取工厂中任何一个InstantiationAwareBeanPostProcessor执行postProcessAfterInstantiation(实例化后)方法,如果返回false不设置属性了
			//
			//applyPropertyValues(beanName, mbd, bw, pvs)
			//应用给定的属性值,解决任何运行时引用
            //到这个bean工厂的其他bean。必须使用深拷贝,所以我们
            //不要永久修改此属性。
			//    PropertyAccessor.setPropertyValues
			//   Method.invoke(obj,args)设置属性
			//
			//
			if (exposedObject != null) {
				exposedObject = initializeBean(beanName, exposedObject, mbd);
				//
				//invokeAwareMethods() 执行bean实现BeanNameAware   BeanClassLoaderAware  BeanFactoryAware的方法
				//applyBeanPostProcessorsBeforeInitialization()  执行工厂中所有的BeanPostProcessor的postProcessBeforeInitialization方法
				//invokeInitMethods()  执行afterPropertiesSet方法
				//  invokeCustomInitMethod()执行配置的init-method方法
				//applyBeanPostProcessorsAfterInitialization() 执行工厂中所有BeanPostProcessor的postProcessAfterInitialization方法
				//
				//
			}
		}
		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 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 {
			registerDisposableBeanIfNecessary(beanName, bean, mbd);
			//把给定的bean添加到工厂的disposable beans列表中,注册它实现的DisposableBean方法或者destroy方法,
			//当工厂关闭时候调用,只使用单例bean
			//
			//
			//
			//
		}
		catch (BeanDefinitionValidationException ex) {
			throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
		}

		return exposedObject;
	}
	

//方法3

AbstractBeanFactory#destroyBean(String beanName, Object beanInstance, RootBeanDefinition mbd){
new DisposableBeanAdapter(beanInstance, beanName, mbd, getBeanPostProcessors(), getAccessControlContext()).destroy();
//DestructionAwareBeanPostProcessor  执行postProcessBeforeDestruction方法
//((DisposableBean) bean).destroy();  执行实现DisposableBean的destroy方法
//invokeCustomDestroyMethod(this.destroyMethod);执行配置的destroy方法
}

最后引用网上两张图片:

spring 笔记5 bean的生命周期,BeanPostProcessor_第1张图片

spring 笔记5 bean的生命周期,BeanPostProcessor_第2张图片


你可能感兴趣的:(spring)