Spring Bean lifecycle?

Let’s start with the Servlet lifecycle: instantiate, initialize init, receive the requested Service, destroy;

The Bean lifecycle in the Spring context is similar as follows:

(1) Instantiate Bean:

For the BeanFactory container, createBean is called when a customer requests an uninitialized bean from the container, or when another uninitialized dependency needs to be injected to initialize the bean. For the ApplicationContext container, when the container is started, all beans are instantiated by getting information from the BeanDefinition object.

(2) Set object properties (dependency injection) :

The instantiated object is wrapped in a BeanWrapper object, and Spring then does dependency injection based on the information in BeanDefinition and the interface provided through BeanWrapper to set properties.

(3) Processing Aware interface:

Spring then checks whether the object implements the xxxAware interface and injects the relevant xxxAware instance into the Bean:

If the Bean already implements the BeanNameAware interface, its setBeanName(String beanId) method is called, passing in the Bean ID value from the Spring configuration file.

② If the Bean already implements the BeanFactoryAware interface, the setBeanFactory() method it implements is called, passing in the Spring factory itself.

If the Bean already implements the ApplicationContextAware interface, the setApplicationContext(ApplicationContext) method is called, passing in the Spring context.

(4) BeanPostProcessor

If want to have some custom processing of beans, you can let the Bean implements the BeanPostProcessor interface, it will call postProcessBeforeInitialization (Object obj, String s) method. Because this method is called at the end of Bean initialization, it can be applied to memory or cache techniques;

(5) InitializingBean and init-method:

If the Bean has the init-method property configured in the Spring configuration file, its configured initialization method is automatically called.

(6) if the Bean implements the BeanPostProcessor interface, will call postProcessAfterInitialization (Object obj, String s) method.

After the above steps are complete, the Bean has been correctly created and is ready to use.

(7) DisposableBean:

When the Bean is no longer needed, it passes through the DisposableBean stage. If the Bean implements the Interface DisposableBean, its implementation destroy() method will be called;

(8) destroy-method:

Finally, if the Bean has the destroy-method property configured in its Spring configuration, its configured destruction method is automatically called.