preface

The life cycle of Spring beans is a hot issue in Spring interviews. This question examines both a micro and a macro understanding of Spring. It is not easy to answer it well! In this article, we hope to start with the source code to help candidates thoroughly fix the Spring Bean lifecycle. The following part of the content is referred to the Spring learning notes. Interested friends can also read it!

The life cycle of a SpringBean

One of the questions we are often asked in interviews is the lifecycle of SpringBeans. In baymax’s words, that is to say, what method is called in order from creation to destruction. When I just started to learn, it is generally to memorize the standard answer, completely do not understand its meaning, but also very easy to forget.

The flow chart is as follows

It looks very complicated and easy to remember and forget.

So I’m going to simulate the SpringBean workflow step by step in code so I don’t forget it again.

Creating a Bean object

Since all say Bean object Bean object, so SpringBean naturally is also an object, we use a simple object to illustrate, so to create an object needs to have a constructor, the object will also have its properties and get, set methods.

 private String field;

 public SpringBean() {
 System.out.println("SpringBean constructor");
 }

 public String getField() {
 System.out.println("SpringBean get method");
 return field;
 }

 public void setField(String field) {
 System.out.println("SpringBean set method");
 this.field = field;
 }
Copy the code

To create a SpringBean, you have to declare the Beam in a configuration file, or you can annotate it.

 <bean class="SpringBean">
	 <property name="field" value="test" />
 </bean>
Copy the code

And then we’re going to initialize this container and see, what do WE get

public static void main(String[] args) {
 ClassPathXmlApplicationContext applicationContext =
 new ClassPathXmlApplicationContext("spring.xml");
 }
Copy the code

Here we can see that when we load the bean inside the container, it calls the constructor and set methods in sequence, which I’m sure most of you know. But beyond that let’s think about our Spring and see if it does anything else, and let’s look at that.

Override the setBeanName method

If the Bean implements some Aware interface, it will inject information related to the Bean container’s underlying attribute level. For example, if we implement the BeanNameAware interface, we need to override its setBeanName method and set the Bean ID in the configuration file

 public void setBeanName(String s) {
 System.out.println("setBeanName:"+s);
 }
Copy the code
<bean id="BeanName" class="SpringBean">
	 <property name="field" value="test" />
 </bean>
Copy the code

Let’s run it and see what happens

As with the rest of the BeanFactoryAware and ApplicationContextAware interfaces, let’s look directly at the result

We can see that the setBeanFactory method is executed first and then the setApplicationContext method

Create a new Bean

Let’s create a new Bean that does global pre-initialization and post-initialization.

For this Bean, we implement the BeanPostProcessor interface

public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
 System.out.println("postProcessBeforeInitialization");
 return bean;
 }

 public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
 System.out.println("postProcessAfterInitialization");
 return null;
 }
Copy the code

Don’t forget to declare the Bean in the configuration file

<bean class="SpringProccesserBean"></bean>
Copy the code

And then let’s try it again

As expected, the pre-method and post-method run after each other. Is that all there is to the Bean? If there was an InitializingBean interface implemented in the Bean, it would be a different story. In addition to overriding the afterPropertiesSet method, we can also specify its init method inside the bean.

 public void afterPropertiesSet() throws Exception {
 System.out.println("afterPropertiesSet");
 }

 public void init(){
 System.out.println("init");
 }
Copy the code

Don’t forget configuration files

<bean id="BeanName" class="SpringBean" init-method="init">
	 <property name="field" value="test" />
 </bean>
Copy the code

As you can see, these two methods are sandwiched between the pre-processor and post-processor, executing the afterPropertiesSet method of the InitializingBean interface first and then the init method of the Bean itself.

At this point, the initialization of a Bean is complete and we are ready to use the Bean.

The Bean destruction process is divided into several steps, one step is to make the destruction interface DisposableBean, rewrite its destruction method destroy, and the other step is the Bean’s own destroy method.

public void destroy() throws Exception {
 System.out.println("DisposableBean");
 }

public void des(){
 System.out.println("des");
 }
Copy the code

Remember to define it in the configuration file

<bean id="BeanName" class="SpringBean" init-method="init" destroy-method="des">
	 <property name="field" value="test" />
 </bean>
Copy the code

Both methods are called when closing is easy, so we call the close method to close the container

public static void main(String[] args) {
 ClassPathXmlApplicationContext applicationContext =
 new ClassPathXmlApplicationContext("spring.xml");

 applicationContext.close();

 }
Copy the code

The results

We see the Destroy method called to the DisposableBean interface and then the Bean’s own destruction method.

This is the life cycle of a SpringBean.

Spring Boot study notes + interview questions

conclusion

The life cycle of Spring beans

Instantiate Bean objects. Set Bean properties. If dependencies are declared through various Aware interfaces, the Bean’s container infrastructure level dependencies are injected. The Aware interface collective includes BeanNameAware, BeanFactoryAware, and ApplicationContextAware to inject the Bean ID, BeanFactory, and ApplicationContext, respectively 4, if realized BeanPostProcesser, calling BeanPostProcesser front-facing initialization method postProcessBeforeInitialization 5, if the InitializingBean interface, Will call the afterPropertiesSet method 6, 7 invoking Bean itself of the init method, call the rear BeanPostProcesser method postProcessAfterInitialization destroyed is created Call DisposableBean’s destroy method and its own before the container closes