About the life cycle of beans in Spring

The life cycle of beans in the Spring container

1. Spring life cycle

  • The so-called life cycle is the process of an object from initialization to destruction. The life cycle of a bean in the Spring container can be summarized as:

    1. initialize(instantiate);
    2. Attribute injection (we usually set attributes for new objects as well);
    3. If the bean implements the BeanNameAuthorware interface, then execute the setBeanName method (the function is to set a unique id for the bean, we get the instance and use it);
    4. If the bean implements the BeanFactoryAware interface, spring will call the setBeanFactory() method to pass in the BeanFactory container;
    5. If the bean implements the ApplicationContextAware interface, spring will call the setApplication() method to pass in the reference of the application context where the bean is located;
    6. If the bean implements the BeanPostProcessor interface, Spring will call the postProcessBeforeInitialization() method of all beans ;
    7. If the bean implements the InitializingBean interface, spring will call their afterPropertiesSet() method. Similarly, if the bean uses the init-method to declare the initialization method, the method will also be called, or use the annotation @PostConstruct to have the same effect.
    8. Corresponding to Article 6 , the same interface, call the postProcessAfterInitialization() method of all beans
    9. Call the method marked by @PreDestroy;
    10. If the bean implements the DisposableBean interface, its destroy() method will be called
  • Diagram
    insert image description here
    Amway here is a book: the fourth edition of spring combat, this picture is exactly the same as the one in the book, after reading it, I personally feel that my understanding of spring is very good (I personally feel that the previous chapters are very well written)

2. Demo bean life cycle

  • Build a springboot project (both spring and springboot can be demonstrated, mainly because you won’t want to play with spring anymore if you use springboot)
  • Write three classes:
    1. TestBean:
package com.example.demo.bean;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.*;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import javax.annotation.PreDestroy;


public class TestBean implements BeanNameAware, BeanFactoryAware, ApplicationContextAware, InitializingBean, DisposableBean {
    
    
    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
    
    
        System.out.println("执行了:setBeanFactory");
    }

    @Override
    public void setBeanName(String s) {
    
    
        System.out.println("执行了:setBeanName");
    }

    @Override
    public void destroy() throws Exception {
    
    
        System.out.println("执行了:destroy");
    }
    @PreDestroy
    public void annodestroy(){
    
    
        System.out.println("执行了:@PreDestroy标注的方法");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
    
    
        System.out.println("执行了:afterPropertiesSet");
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    
    
        System.out.println("执行了:setApplicationContext");
    }
}
	

too long? In fact, you don’t need to look at most of them. You just need to look at what interfaces are implemented and compare them with the pictures. It’s also very convenient to write and understand by yourself.

  1. TestPostProcessorBean:
package com.example.demo.bean;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;


public class TestPostProcessorBean implements BeanPostProcessor {
    
    
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    
    
        System.out.println("执行了:postProcessBeforeInitialization");
        return null;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    
    
        System.out.println("执行了:postProcessAfterInitialization");
        return null;
    }
}

It should be noted here that the two methods of the BeanPostProcessor interface will be executed by all beans. Why should it be taken out separately here? The BeanPostProcessor class is to allow some operations before and after creation when creating other classes. If it is written on TestBean, it is generally The postProcessBeforeInitialization() and postProcessAfterInitialization() methods will not be called. The reason is that before the bean defined by the container initialization is created, the container will search for all BeanPostProcessors to create custom classes. Since the BeanPostProcessor interface is implemented, the BeanPostProcessor will be created and registered at this time. In the source code, in the registration BeanPostProcessor will perform the getBean operation, that is, create a custom bean. Since the default is the singleton mode, the postProcessBeforeInitialization() and postProcessAfterInitialization() methods will not be called again if the acquisition is performed again later, because they have been placed in the spring cache and obtained directly without an instance, so there is no call.

  1. TestConfig:
package com.example.demo.config;

import com.example.demo.bean.TestBean;
import com.example.demo.bean.TestPostProcessorBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class TestConfig {
    
    
   @Bean("TestBean")
   public TestBean getTestBean(){
    
    
       return new TestBean();
   }

   @Bean("TestPostProcessorBean")
   public TestPostProcessorBean getPostProcessorBean(){
    
    
       return new TestPostProcessorBean();
   }
}

3. Code testing

package com.example.demo;

import com.example.demo.bean.TestBean;
import com.example.demo.config.TestConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;


public class TestMain {
    
    
    public static void main(String[] args) {
    
    
        AnnotationConfigApplicationContext ap=new AnnotationConfigApplicationContext(TestConfig.class);
        ap.getBean("TestBean", TestBean.class);
        ap.close();
    }
}

Result:
insert image description here
Note that the main method must remember to destroy the context, otherwise the destroy method cannot be reached

Guess you like

Origin blog.csdn.net/chenyingchuan996/article/details/105274320