What is the lifecycle of a spring bean?
The lifecycle of a Spring Bean can be divided into the following stages:
- Instantiation: When the Spring container loads the configuration file, it will create instances of beans based on the definitions in the file. The instantiation can be done through constructor instantiation or factory method instantiation.
- Property injection: After instantiating a bean, Spring container injects the property values defined in the configuration file into the bean instance, which can be done through setter methods.
- Initialization: After the Bean instance is created and its properties are injected, the Spring container will call the Bean’s initialization method, which can be achieved by either defining an initialization method in the Bean class or using annotations.
- After initialization is completed, the Bean instance can be used to call the methods of the Bean object for business processing.
- Destruction: When the container is shut down, the destroy method of the Bean will be invoked, which can be implemented by defining a destroy method in the Bean class or using annotations.
It is worth noting that the initialization and destruction methods of Bean can be defined by implementing the InitializingBean and DisposableBean interfaces, or by using the initMethod and destroyMethod attributes of the @Bean annotation. Alternatively, you can also specify initialization and destruction methods using the @PostConstruct and @PreDestroy annotations.