浅谈SpringBean的生命周期

2021-07-27 11:17:35 浏览数 (1)

总述

代码语言:javascript复制
Spring Bean的生命周期是一个老生常谈的问题,笔者之前因为面试也看过不少相关的文章。发现每个文章写得都不太一样,有的多有的少。最近在重翻Spring源码的时候,发现`org.springframework.beans.factory.BeanFactory`中对整个过程在注释中写得非常详细,遂整理下来,方便后续查看。

show me the code

代码语言:javascript复制
下面直接给出BeanFactory上面的注释代码:
代码语言:javascript复制
Bean factory implementations should support the standard bean lifecycle interfacesas far as possible. The full set of initialization methods and their standard order is: 
1.BeanNameAware's setBeanName 
2.BeanClassLoaderAware's setBeanClassLoader 
3.BeanFactoryAware's setBeanFactory 
4.EnvironmentAware's setEnvironment 
5.EmbeddedValueResolverAware's setEmbeddedValueResolver 
6.ResourceLoaderAware's setResourceLoader(only applicable when running in an application context) 
7.ApplicationEventPublisherAware's setApplicationEventPublisher(only applicable when running in an application context) 
8.MessageSourceAware's setMessageSource(only applicable when running in an application context) 
9.ApplicationContextAware's setApplicationContext(only applicable when running in an application context) 
10.ServletContextAware's setServletContext(only applicable when running in a web application context) 
11.postProcessBeforeInitialization methods of BeanPostProcessors 
12.InitializingBean's afterPropertiesSet 
13.a custom init-method definition 
14.postProcessAfterInitialization methods of BeanPostProcessors 

On shutdown of a bean factory, the following lifecycle methods apply: 
1.postProcessBeforeDestruction methods of DestructionAwareBeanPostProcessors 
2.DisposableBean's destroy 
3.a custom destroy-method definition 

一点说明

代码语言:javascript复制
其实Spring还支持@PostConstruct和@PreDestroy注解,只不过这两个注解的定义其实在javax.annotation包中,不归属于Spring的包。Spring只是在org.springframework.context.annotation.CommonAnnotationBeanPostProcessor中处理了这两个注解。具体代码如下:
代码语言:javascript复制
public CommonAnnotationBeanPostProcessor() {
	setOrder(Ordered.LOWEST_PRECEDENCE - 3);
	setInitAnnotationType(PostConstruct.class);
	setDestroyAnnotationType(PreDestroy.class);
	ignoreResourceType("javax.xml.ws.WebServiceContext");
}
代码语言:javascript复制
设置处理的注解类型
代码语言:javascript复制
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
	LifecycleMetadata metadata = findLifecycleMetadata(bean.getClass());
	try {
		metadata.invokeInitMethods(bean, beanName);
	}
	catch (InvocationTargetException ex) {
		throw new BeanCreationException(beanName, "Invocation of init method failed", ex.getTargetException());
	}
	catch (Throwable ex) {
		throw new BeanCreationException(beanName, "Failed to invoke init method", ex);
	}
	return bean;
}
代码语言:javascript复制
@Override
public void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException {
	LifecycleMetadata metadata = findLifecycleMetadata(bean.getClass());
	try {
		metadata.invokeDestroyMethods(bean, beanName);
	}
	catch (InvocationTargetException ex) {
		String msg = "Invocation of destroy method failed on bean with name '"   beanName   "'";
	if (logger.isDebugEnabled()) {
		logger.warn(msg, ex.getTargetException());
	}
	else {
		logger.warn(msg   ": "   ex.getTargetException());
	}
	}
	catch (Throwable ex) {
		logger.error("Failed to invoke destroy method on bean with name '"   beanName   "'", ex);
	}
}
代码语言:javascript复制
子类InitDestroyAnnotationBeanPostProcessor实现了DestructionAwareBeanPostProcessor, 该接口的定义如下:
代码语言:javascript复制
public interface DestructionAwareBeanPostProcessor extends BeanPostProcessor

0 人点赞