zoukankan      html  css  js  c++  java
  • 浅谈SpringBean的生命周期

    总述

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

    show me the code

    下面直接给出BeanFactory上面的注释代码:
    
    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 
    

    一点说明

    其实Spring还支持@PostConstruct和@PreDestroy注解,只不过这两个注解的定义其实在javax.annotation包中,不归属于Spring的包。Spring只是在org.springframework.context.annotation.CommonAnnotationBeanPostProcessor中处理了这两个注解。具体代码如下:
    
    public CommonAnnotationBeanPostProcessor() {
    	setOrder(Ordered.LOWEST_PRECEDENCE - 3);
    	setInitAnnotationType(PostConstruct.class);
    	setDestroyAnnotationType(PreDestroy.class);
    	ignoreResourceType("javax.xml.ws.WebServiceContext");
    }
    
    设置处理的注解类型
    
    @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;
    }
    
    @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);
    	}
    }
    
    子类InitDestroyAnnotationBeanPostProcessor实现了DestructionAwareBeanPostProcessor, 该接口的定义如下:
    
    public interface DestructionAwareBeanPostProcessor extends BeanPostProcessor
    
    黎明前最黑暗,成功前最绝望!
  • 相关阅读:
    如何仅仅修改每一页的页眉
    resize
    Linux搭建深度学习环境
    Image.open、cv2.imread
    any、all
    cookie
    any、all
    库文件
    出来混总要还的,要提醒自己提高核心竞争力
    “行百里者半九十”(现在才逐渐真正理解这些道理)
  • 原文地址:https://www.cnblogs.com/Kidezyq/p/15048166.html
Copyright © 2011-2022 走看看