The life cycle of a bean in Spring mainly includes four stages: instantiating the bean --> Bean attribute filling --> Initializing the bean --> Destroying the bean
First, instantiate the bean. When the client requests a bean that has not been initialized from the container, or when the bean is initialized, another dependency that has not been initialized needs to be injected, the container will call the doCreateBean() method for instantiation, which is actually creating a bean object through reflection.
After the bean instance is created, the property is filled in the bean object, that is, the other bean objects that the bean depends on.
After the attribute filling is completed, the initialization bean operation is performed. The initialization stage can be divided into several steps:
-
Methods to execute Aware interface
Spring will detect whether the object is implementedxxxAwareInterface, through Aware-type interface, we can get some resources of Spring container. If implemented
BeanNameAware interface can obtain BeanName, and implement BeanFactoryAware interface can obtain factory object BeanFactory, etc. -
Execute the preprocessing method of BeanPostProcessor postProcessBeforelnitialization() to perform some custom preprocessing of the bean
-
Determine whether the Bean implements the InitializingBean interface. If it is implemented, the lnitializingBean's afeterPropertiesSet() initialization method will be executed;
-
Execute user-defined initialization methods, such as init-method, etc.;
-
Postprocessing method for executing BeanPostProcessor postProcessAfterinitialization()
After the initialization is completed, the bean is successfully created. After that, this bean can be used. When the bean is no longer needed, it will be destroyed.
- First, determine whether the Bean implements the DestructionAwareBeanPostProcessor interface. If it is implemented, the DestructionAwareBeanPostProcessor postprocessor will be executed.
- Secondly, we will determine whether the Bean implements the DisposableBean interface. If it is implemented, the destroy() method will be called.
- Finally, determine whether this bean has customized destruction methods such as dlestroy-method. If so, the configured destruction method will be automatically called;