《Yangzai的知识地图》- Bean的生命周期

Spring 中的bean 的生命周期有哪些步骤

一、概述

简答来说分四步。实例化【Instantiation】?属性填充【populateBean】?初始化【initializeBean】?销毁【destroy】

详细如图:

在这里插入图片描述

二、细节:

1、实例化前的准备工作

首先这些所谓的Bean无论是通过XML配置亦或是注解形式都讲扫描后加载并赋值给BeanDefinition然后放入Map中进行存储,此时工厂中是没有Bean的。

2、关于InstantiationAwareBeanPostProcessor

实例化前会调用org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation方法。

		try {
			// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
			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);
		}

还有org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor#postProcessAfterInstantiation这个是在实例化之后执行的。

3、属性填充

属性填充前先会执行上面说到的org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor#postProcessAfterInstantiation

		// 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.
		if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
			for (BeanPostProcessor bp : getBeanPostProcessors()) {
				if (bp instanceof InstantiationAwareBeanPostProcessor) {
					InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
					if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
						return;
					}
				}
			}
		}

然后填充BeanDefinition中的属性到实例Bean中

4、初始化

初始化的时候会先执行几个Aware方法如BeanNameAware、BeanClassLoaderAware、BeanFactoryAware,

执行Bean后置处理org.springframework.beans.factory.config.BeanPostProcessor#postProcessBeforeInitialization

然后进行初始化操作

执行Bean后置处理org.springframework.beans.factory.config.BeanPostProcessor#postProcessAfterInitialization

		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()) {
			wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
		}

		try {
			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()) {
			wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
		}

5、销毁

当Bean不再需要时,会经过清理阶段,如果Bean实现了DisposableBean这个接口,会调用其实现的destroy()方法;如果这个Bean的Spring配置中配置了destroy-method属性,会自动调用其配置的销毁方法。

单例Bean会放在单例池中。


版权声明:本文为YangzaiLeHeHe原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。