Preface
Spring's ioc container is very powerful, responsible for the creation and management of Spring's beans and other functions. Spring beans are an important part of the entire Spring application. Understanding the life cycle of Spring beans will be of great help to us understand the entire spring framework.
BeanFactory and ApplicationContext are two important containers of Spring. The former provides the most basic support for dependency injection, while the latter expands its functions based on inheriting the former, such as adding functions such as event propagation, resource access and international message access. This article mainly introduces the life cycle of beans in two containers ApplicationContext and BeanFactory.
First look at the life cycle chart:
Let’s talk about the life cycle before we talk about it:
Spring only helps us manage the full life cycle of singleton model beans. For prototype beans, Spring will no longer manage subsequent life cycles after they are created and handed over to the user.
Annotation method
There are several stages when initializing the bean. First, you can use the annotation @PostConstruct and @PreDestroy to call it in the creation and destruction stage of the bean:
@Componentpublic class AnnotationBean { private final static Logger LOGGER = LoggerFactory.getLogger(AnnotationBean.class); @PostConstruct public void start(){ LOGGER.info("AnnotationBean start"); } @PreDestroy public void destroy(){ LOGGER.info("AnnotationBean destroy"); }}InitializingBean, DisposableBean interface
You can also implement the two interfaces of InitializingBean and DisposableBean, which are also called during the initialization and destruction stages:
@Servicepublic class SpringLifeCycleService implements InitializingBean,DisposableBean{ private final static Logger LOGGER = LoggerFactory.getLogger(SpringLifeCycleService.class); @Override public void afterPropertiesSet() throws Exception { LOGGER.info("SpringLifeCycleService start"); } @Override public void destroy() throws Exception { LOGGER.info("SpringLifeCycleService destroy"); }}Custom initialization and destruction methods
You can also customize methods for calling during the initialization and destruction stages:
@Configurationpublic class LifeCycleConfig { @Bean(initMethod = "start", destroyMethod = "destroy") public SpringLifeCycle create(){ SpringLifeCycle springLifeCycle = new SpringLifeCycle() ; return springLifeCycle ; }}public class SpringLifeCycle{ private final static Logger LOGGER = LoggerFactory.getLogger(SpringLifeCycle.class); public void start(){ LOGGER.info("SpringLifeCycle start"); } public void destroy(){ LOGGER.info("SpringLifeCycle destroy"); }}The above is configured in SpringBoot in this way, and it can also be used if it is original XML-based:
<bean init-method="start" destroy-method="destroy"></bean>
to achieve the same effect.
Implement *Aware interface
*Aware interface can be used to obtain some objects in Spring when initializing beans, such as obtaining Spring context.
@Componentpublic class SpringLifeCycleAware implements ApplicationContextAware { private final static Logger LOGGER = LoggerFactory.getLogger(SpringLifeCycleAware.class); private ApplicationContext applicationContext ; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext ; LOGGER.info("SpringLifeCycleAware start"); }}In this way, the setApplicationContext method will be called in the initialization of springLifeCycleAware bean and the applicationContext object can be obtained.
BeanPostProcessor Enhanced Processor
Implement the BeanPostProcessor interface. All beans in Spring will call two methods in the interface when initializing, which can be used to process some special beans:
@Componentpublic class SpringLifeCycleProcessor implements BeanPostProcessor { private final static Logger LOGGER = LoggerFactory.getLogger(SpringLifeCycleProcessor.class); /** * Called before pre-initialization* @param bean * @param beanName * @return * @throws BeansException */ @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if ("annotationBean".equals(beanName)){ LOGGER.info("SpringLifeCycleProcessor start beanName={}",beanName); } return bean; } /** * Post-initialization bean Initialization Complete call* @param bean * @param beanName * @return * @throws BeansException */ @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if ("annotationBean".equals(beanName)){ LOGGER.info("SpringLifeCycleProcessor end beanName={}",beanName); } return bean; }}Observation results after execution:
018-03-21 00:40:24.856 [restartedMain] INFO ccspSpringLifeCycleProcessor - SpringLifeCycleProcessor start beanName=annotationBean2018-03-21 00:40:24.860 [restartedMain] INFO ccspring.annotation.AnnotationBean - AnnotationBean start2018-03-21 00:40:24.861 [restartedMain] INFO ccspSpringLifeCycleProcessor - SpringLifeCycleProcessor end beanName=annotationBean2018-03-21 00:40:24.864 [restartedMain] INFO ccsaware.SpringLifeCycleAware - SpringLifeCycleAware start2018-03-21 00:40:24.867 [restartedMain] INFO ccspring.SpringLifeCycleService - SpringLifeCycleService start2018-03-21 00:40:24.887 [restartedMain] INFO ccspring.SpringLifeCycle - SpringLifeCycle start2018-03-21 00:40:25.062 [restartedMain] INFO osbdaOptionalLiveReloadServer - LiveReload server is running on port 357292018-03-21 00:40:25.122 [restartedMain] INFO osjeaAnnotationMBeanExporter - Registering beans for JMX exposure on startup2018-03-21 00:40:25.140 [restartedMain] INFO com.crossoverjie.Application - Started Application in 2.309 seconds (JVM running for 3.681)2018-03-21 00:40:25.143 [restartedMain] INFO com.crossoverjie.Application - start ok!2018-03-21 00:40:25.153 [Thread-8] INFO oscaAnnotationConfigApplicationContext - Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@3913adad: startup date [Wed Mar 21 00:40:23 CST 2018]; root of context hierarchy2018-03-21 00:40:25.155 [Thread-8] INFO osjeaAnnotationMBeanExporter - Unregistering JMX-exposed beans on shutdown2018-03-21 00:40:25.156 [Thread-8] INFO ccspring.SpringLifeCycle - SpringLifeCycle destroy2018-03-21 00:40:25.156 [Thread-8] INFO ccservice.SpringLifeCycleService - SpringLifeCycleService destroy2018-03-21 00:40:25.156 [Thread-8] INFO ccspring.annotation.AnnotationBean - AnnotationBean destroy
Until Spring context is destroyed, a custom destroy method and the destroy() method that implements DisposableBean will be called.
Summarize
The above is the Spring Bean life cycle introduced by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!