对spring框架中bean生命周期的简单介绍

spring中bean的生命周期分为四各阶段:实例化、属性赋值(注入)、初始化、销毁。前三个阶段的核心方法位于AbstractAutowireCapableBeanFactory#doCreateBean方法中:

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

	// Instantiate the bean.
	BeanWrapper instanceWrapper = null;
	if (mbd.isSingleton()) {
		instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
	}
	if (instanceWrapper == null) {
		//createBeanInstance方法对应实例化阶段
		instanceWrapper = createBeanInstance(beanName, mbd, args);
	}
	Object bean = instanceWrapper.getWrappedInstance();
	Class<?> beanType = instanceWrapper.getWrappedClass();
	if (beanType != NullBean.class) {
		mbd.resolvedTargetType = beanType;
	}

	//...
	
	// Initialize the bean instance.
	Object exposedObject = bean;
	try {
	
		//populateBean方法对应属性赋值阶段
		populateBean(beanName, mbd, instanceWrapper);

		//initializeBean方法对应初始化阶段
		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);
		}
	}

	//...
	
	return exposedObject;
}

这个方法中的createBeanInstance()populateBean()initializeBean()分别对应实例化、属性赋值、初始化三个阶段

createBeanInstance()

这个方法中,spring容器会根据工厂方法依据构造方法装配(构造注入)简单实例化(无参构造) 三种方式中的一种实例化对象

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

	//根据自定义的instanceSupplier实例化对象
	Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
	if (instanceSupplier != null) {
		return obtainFromSupplier(instanceSupplier, beanName);
	}

	//根据工厂方法实例化对象
	if (mbd.getFactoryMethodName() != null) {
		return instantiateUsingFactoryMethod(beanName, mbd, args);
	}

	//...

	//选择构造注入的构造方法并实例化对象
	
	// Candidate constructors for autowiring?
	Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
	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);
}

populateBean()

在属性赋值的过程中,会根据xml中property标签配置的内容进行赋值,如果xml注入bean时配置了autowire属性,也会根据配置的注入模式(名称、类型)进行依赖注入,此外,过程中也会根据@AutoWired和@Value注解对对应属性进行赋值

protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {

	//获取xml中property标签中配置的属性
	PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);

	//获取xml中配置的autowire信息,根据名称或类型为当前实例化的bean注入其依赖的bean
	int resolvedAutowireMode = mbd.getResolvedAutowireMode();
	if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
		MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
		// Add property values based on autowire by name if applicable.
		if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
			autowireByName(beanName, mbd, bw, newPvs);
		}
		// Add property values based on autowire by type if applicable.
		if (resolvedAutowireMode == 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();
		}
		
		//根据bean的postProcessor对属性进行处理,包括根据@AutoWired和@Value注解进行注入、赋值
		for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
			PropertyValues pvsToUse = bp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
			if (pvsToUse == null) {
				if (filteredPds == null) {
					filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
				}
				pvsToUse = bp.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) {
		//将xml中配置的property标签中的值赋值给对应属性
		applyPropertyValues(beanName, mbd, bw, pvs);
	}
}

initializeBean()

在初始化的过程中,依次调用了当前bean实现的Aware接口下的方法、在初始化前执行的postProcessor、自定义的init-method方法、在初始化后执行的postProcessor

protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
	if (System.getSecurityManager() != null) {
		AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
			invokeAwareMethods(beanName, bean);
			return null;
		}, getAccessControlContext());
	}
	else {
		//调用当前bean实现的Aware接口下的方法
		invokeAwareMethods(beanName, bean);
	}

	Object wrappedBean = bean;
	//调用初始化前执行的postProcessor
	if (mbd == null || !mbd.isSynthetic()) {
		wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
	}

	try {
		//调用设置的init-method方法
		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()) {
		//调用初始化后执行的postProcessor
		wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
	}

	return wrappedBean;
}

  最后一个销毁阶段对于单例的bean来说,在spring容器关闭时由容器销毁;对于多例的bean来说,spring容器关闭时容器不会自动销毁,由java的GC机制回收。可以通过实现DisposableBean接口、定义destroy-method方法、使用@PreDestroy注解等方式来干预bean的销毁
  以上是对bean生命周期的四个阶段的简单介绍,每个阶段还有很多细节的处理。此外,spring还提供了很多扩展点,允许开发人员干预bean的生命周期的不同阶段。

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值