In this tutorial we are going to see the Spring Bean life Cycle.
When Bean instantiated, it may required to perform some initialization to get it into a usable state.When the bean no longer required and removed from container some clean up may be required.
For above mention operation some list of activities take place behind the scenes.
Spring Lifecycle Callbacks
To interact with the container's management of the bean lifecycle, you can implement the Spring InitializingBean and DisposableBean interfaces. The container calls afterPropertiesSet() for the former and destroy() for the latter to allow the bean to perform certain actions upon initialization and destruction of your beans.
Internally, the Spring Framework uses BeanPostProcessor implementations to process any callback interfaces it can find and call the appropriate methods. If you need custom features or other lifecycle behavior Spring does not offer out-of-the-box, you can implement a BeanPostProcessor yourself.
In addition to the initialization and destruction callbacks, Spring-managed objects may also implement the Lifecycle interface so that those objects can participate in the startup and shutdown process as driven by the container's own lifecycle.
The JSR-250 @PostConstruct and @PreDestroy annotations are generally considered best practice for receiving lifecycle callbacks in a modern Spring application. Using these annotations means that your beans are not coupled to Spring specific interfaces.
If you don't want to use the JSR-250 annotations but you are still looking to remove coupling consider the use of init-method and destroy-method object definition metadata.
We will see the following life cycle callback event in upcoming chapter.
- Initialization callbacks
- Destruction callbacks
- Default initialization and destroy methods
- @PostConstruct
- @PreDestroy
- Startup and Shutdown callbacks
0 comments:
Post a Comment