Talk about my understanding of the spring bean life cycle

preface

Spring's IOC container is very powerful and is responsible for the creation and management of spring beans. Spring beans are a very important part of the whole spring application. Understanding the life cycle of spring beans will be very helpful for us to understand the whole spring framework.

Beanfactory and ApplicationContext are two very important containers in spring. The former provides the most basic support for dependency injection, while the latter expands its functions on the basis of inheriting the former, such as adding functions such as event propagation, resource access and international message access. This paper mainly introduces the bean life cycle of ApplicationContext and beanfactory containers.

First, take a look at the life cycle diagram:

Before we talk about the life cycle, we need to make it clear:

Spring only helps us manage the complete life cycle of singleton pattern beans. For prototype beans, spring will not manage the subsequent life cycle after they are created and handed over to the user.

Annotation method

Bean initialization will go through several stages. First, you can use the annotation @ postconstruct, @ predestroy to call in the bean creation and destruction stages:

Initializingbean, disposablebean interface

You can also implement the initializingbean and disposablebean interfaces, which are also called in the initialization and destruction stages:

Custom initialization and destruction methods

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

The above can be configured in springboot in this way. If it is original XML based, it can also be used:

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.

In this way, the bean initialization of springlifecycleware will call the setapplicationcontext method and obtain the ApplicationContext object.

Beanpostprocessor enhanced processor

Implement the beanpostprocessor interface. All beans in spring will call two methods in the interface during initialization, which can be used to process some special beans:

Observations after execution:

Until the spring context is destroyed, the custom destruction method and the destroy () method that implements disposablebean will be called.

summary

The above is the spring bean life cycle introduced by Xiaobian. I hope it will be helpful to you. If you have any questions, please leave me a message, and Xiaobian will reply to you in time. Thank you very much for your support for the programming tips website!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>