Spring Bean Life Cycle
A Spring bean's life cycle is simple to comprehend. When a bean is instantiated, some initialization may be required to get it into a useable state. When the bean is no longer needed and taken from the container, some cleanup may be necessary.
We declare the with init method and destroy-method parameters to describe setup and teardown for a bean. The init-method attribute provides a process that will be called immediately after the bean is instantiated. In the same way, the destroy method provides a function invoked right before a bean is deleted from the container.
Callbacks throughout the life cycle
The spring bean factory controls the creation and destruction of beans. It supports call back methods to execute custom code, which can be divided into two categories:
- Methods for receiving callbacks Post-initialization
- Callback mechanisms used Pre-destruction
Callback mechanisms for the life cycle
The Spring Framework provides the following four ways to trick the life cycle cycle of beans:
- InitializingBean and Disposable Interfaces for bean callbacks
- Interfaces for bean callbacksÂ
- 3. @PreDestroy and @PostConstruct annotations in the bean configuration file
- custom destroy() and init()methods
Spring codes: