欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

《Spring设计思想》13-bean的实例化和初始化阶段概览

程序员文章站 2022-05-23 16:22:11
...

前面几节终于讲完了bean的实例化过程,围绕着bean的实例化,spring做了众多的准备工作:

1-加载beanDefinition

2-mergeBeanDefinition

3-加载bean的Class

4-调用InstantiationAwareBeanPostProcessor的postProcessBeforeInstantiation方法打断实例化过程

5-实例化

6-调用InstantiationAwareBeanPostProcessor的postProcessAfterInstantiation方法打断bean的PropertyValues赋值

7-调用InstantiationAwareBeanPostProcessor的postProcessrProperties方法,修改bean的Propertyvalues的值

8-applyPropertyValue

那么接下来bean的实例化阶段已经完成。进入下一个阶段-初始化

初始化的路程也必定艰辛坎坷,这一次我们仔细观察一下initializeBean(beanName,exposeObject,mbd);

	/**
	 * Initialize the given bean instance, applying factory callbacks
	 * as well as init methods and bean post processors.
	 */
	protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
		
        //调用bean实现的Aware接口方法
		invokeAwareMethods(beanName, bean);
		

		Object wrappedBean = bean;
		if (mbd == null || !mbd.isSynthetic()) {
        //   调用BeanPostProcessor的beforeInitialization方法
			wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
		}

		try {
        // 调用初始化方法
			invokeInitMethods(beanName, wrappedBean, mbd);
		}
		// 调用beanPostProcessor的afterInitialization方法
		if (mbd == null || !mbd.isSynthetic()) {
			wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
		}

		return wrappedBean;
	}

整个方法看起来就四个重点:

1-invokeAwareMethods(beanName,bean);--调用bean实现的三个Aware接口BeanNameAware/BeanClassLoaderAware/BeanFactoryAware

2-applyBeanPostProcessorsBeforeInitialization(wrapedBean,beanName);--执行BeanPostProcessor的postProcessBeforeInitalization方法

3-invokeInitMethod(beanName,wrappedBean,mbd);--调用Bean实现的InitializingBean接口,调用自定义的初始化方法

4-applyBeanPostPeocessorsAfrerInitialization(wrappedBean,beanName);--调用BeanPostProcessor的postProcessAfterInitialization方法

以上就是bean的初始化的大体概览,下一节我们仔细看一下invokeAwareMethods到底发生了啥