preface

The life cycle of Spring beans plays an important role in the overall Spring, and understanding this will help you understand Spring better.

Let’s start with the lifecycle diagram:

Before we move on to the life cycle, one thing needs to be clear:

Spring only manages the full life cycle of singleton beans. For Prototype beans, Spring doesn’t manage the rest of the life cycle after they are created and handed over to the consumer.

Annotation way

There are several phases during bean initialization. First, we can use the @postConstruct, @PreDestroy annotations to make calls during bean creation and destruction phases:

@Component
public class AnnotationBean {
    private final static Logger LOGGER = LoggerFactory.getLogger(AnnotationBean.class);

    @PostConstruct
    public void start(a){
        LOGGER.info("AnnotationBean start");
    }

    @PreDestroy
    public void destroy(a){
        LOGGER.info("AnnotationBean destroy"); }}Copy the code

InitializingBean and DisposableBean interfaces

Also can realize InitializingBean DisposableBean these two interfaces, is also in the initialization and destruction stage calls:

@Service
public class SpringLifeCycleService implements InitializingBean.DisposableBean{
    private final static Logger LOGGER = LoggerFactory.getLogger(SpringLifeCycleService.class);
    @Override
    public void afterPropertiesSet(a) throws Exception {
        LOGGER.info("SpringLifeCycleService start");
    }

    @Override
    public void destroy(a) throws Exception {
        LOGGER.info("SpringLifeCycleService destroy"); }}Copy the code

Custom initialization and destruction methods

You can also customize methods to be called during initialization and destruction:

@Configuration
public class LifeCycleConfig {


    @Bean(initMethod = "start", destroyMethod = "destroy")
    public SpringLifeCycle create(a){
        SpringLifeCycle springLifeCycle = new SpringLifeCycle() ;

        returnspringLifeCycle ; }}public class SpringLifeCycle{

    private final static Logger LOGGER = LoggerFactory.getLogger(SpringLifeCycle.class);
    public void start(a){
        LOGGER.info("SpringLifeCycle start");
    }


    public void destroy(a){
        LOGGER.info("SpringLifeCycle destroy"); }}Copy the code

This can be configured in SpringBoot, or if it is raw XML-based:

<bean class="com.crossoverjie.spring.SpringLifeCycle" init-method="start" destroy-method="destroy">
</bean>
Copy the code

To achieve the same effect.

Implement the *Aware interface

* The Aware interface can be used to get objects in Spring, such as the Spring context, when initializing a bean.

@Component
public 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"); }}Copy the code

The setApplicationContext method is then called in the springLifeCycleAware bean initialization and the applicationContext object is obtained.

BeanPostProcessor enhances the processor

BeanPostProcessor (BeanPostProcessor) : BeanPostProcessor (BeanPostProcessor) : BeanPostProcessor (BeanPostProcessor) : BeanPostProcessor

@Component
public class SpringLifeCycleProcessor implements BeanPostProcessor {
    private final static Logger LOGGER = LoggerFactory.getLogger(SpringLifeCycleProcessor.class);

    /** * preinitialization * is called before 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;
    }

    /** * the bean initializes to complete the 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);
        }
        returnbean; }}Copy the code

Observation results after execution:

The 018-03-21 00:40:24. 856 / restartedMain INFO C.C.S.P.S pringLifeCycleProcessor - SpringLifeCycleProcessor start BeanName = annotationBean 00:40:24 2018-03-21. 860 / restartedMain INFO C.C.S pring. The annotation. AnnotationBean - AnnotationBean start the 2018-03-21 00:40:24. 861 / restartedMain INFO C.C.S.P.S pringLifeCycleProcessor - SpringLifeCycleProcessor end beanName=annotationBean 2018-03-21 00:40:24.864 [restartedMain] INFO C.C.S.A ware. SpringLifeCycleAware - SpringLifeCycleAware start the 2018-03-21 00:40:24. 867 / restartedMain INFO C.C.S.S ervice. SpringLifeCycleService - SpringLifeCycleService start the 2018-03-21 00:40:24. 887 / restartedMain INFO C.C.S pring. SpringLifeCycle - SpringLifeCycle start the 2018-03-21 00:40:25. 062 / restartedMain INFO O.S.B.D.A.O ptionalLiveReloadServer - LiveReload server is running on port 35729 2018-03-21 00:40:25 122 [restartedMain] INFO o.s.j.e.a.AnnotationMBeanExporter - Registering beansforJMX exposure on startup 00:40:25. 2018-03-21 140 [restartedMain] INFO com. Crossoverjie. Application - Started Applicationin2.309 seconds (JVM is runningfor3.681) the 2018-03-21 00:40:25. 143 / restartedMain INFO. Com crossoverjie. Application - start ok! The 2018-03-21 00:40:25. 153 [Thread - 8] INFO O.S.C.A.A nnotationConfigApplicationContext - Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@3913adad: startup date [Wed Mar 21 00:40:23 CST 2018]; [Thread root of the context hierarchy 00:40:25 2018-03-21. 155-8] INFO O.S.J.E.A.A nnotationMBeanExporter - Unregistering JMX - exposed beans on shutdown 00:40:25 2018-03-21. 156 / Thread - 8 INFO C.C.S pring. SpringLifeCycle - SpringLifeCycle Destroy the 2018-03-21 00:40:25. 156 [Thread - 8] INFO C.C.S.S ervice. SpringLifeCycleService - SpringLifeCycleService destroy The 2018-03-21 00:40:25. 156 [Thread - 8] INFO C.C.S pring. The annotation. AnnotationBean - AnnotationBean destroyCopy the code

The custom destruction method and destroy() method that DisposableBean will be called until the Spring context is destroyed.

extra

Recently in the summary of some Java related knowledge points, interested friends can maintain together.

Address: github.com/crossoverJi…