Explain the life cycle of beans in the Spring framework

In traditional Java applications, the life cycle of a bean is very simple. Use the Java keyword new to instantiate the bean, and then the bean can be used. Once the bean is no longer used, it is automatically garbage collected by Java. In contrast, the life cycle of the bean in the Spring container is relatively more complicated. It is very important to correctly understand the life cycle of Spring beans, because you may want to use the extension points provided by Spring to customize the bean creation process. The following figure shows a typical life cycle process of bean loading into the Spring application context.

The bean has gone through several stages from creation to destruction in the Spring container, and each stage can be customized for how Spring manages the bean.

As you can see, the bean factory performs several startup steps before the bean is ready.

We describe the above picture in detail:

Spring instantiates the bean;

Spring injects values ​​and bean references into the corresponding properties of the bean;

If the bean implements the BeanNameAware interface, Spring will pass the bean ID to the setBean-Name() method;

If the bean implements the BeanFactoryAware interface, Spring will call the setBeanFactory() method to pass in the BeanFactory container instance;

If the bean implements the ApplicationContextAware interface, Spring will call the setApplicationContext() method to pass in a reference to the application context where the bean is located;

If the bean implements the BeanPostProcessor interface, Spring will call their post-ProcessBeforeInitialization() method;

If the bean implements the InitializingBean interface, Spring will call their after-PropertiesSet() method. Similarly, if the bean uses the initmethod to declare the initialization method, the method will also be called;

If the bean implements the BeanPostProcessor interface, Spring will call their post-ProcessAfterInitialization() method;

At this point, the beans are ready to be used by the application, and they will remain in the application context until the application context is destroyed;

If the bean implements the DisposableBean interface, Spring will call its destroy() interface method. Similarly, if the bean declares a destroy method using destroy-method, that method will also be called.

Now you have understood how to create and load a Spring container. But an empty container doesn't have much value. Before you put things in, there is nothing in it. In order to benefit from Spring's DI (Dependency Injection), we must assemble the application object into the Spring container.

Guess you like

Origin blog.csdn.net/qq_41489540/article/details/114592897