Bean Lifecycle??
When container starts – a Spring bean needs to be instantiated, based on Java or XML bean definition. It may also be required to perform some post-initialization steps to get it into a usable state. Same bean life cycle is for spring boot applications as well.
After that, when the bean is no longer required, it will be removed from the IoC container.
Spring bean factory is responsible for managing the life cycle of beans created through spring container.
1.1. Life cycle callbacks
Spring bean factory controls the creation and destruction of beans. To execute some custom code, it provides the call back methods which can be categorized broadly in two groups:
- Post-initialization call back methods
- Pre-destruction call back methods
1.1. Life cycle in diagram
2. Life cycle callback methods
Spring framework provides following 4 ways for controlling life cycle events of a bean:
InitializingBean
andDisposableBean
callback interfaces- *Aware interfaces for specific behavior
- Custom
init()
anddestroy()
methods in bean configuration file @PostConstruct
and@PreDestroy
annotations
2.1. InitializingBean and DisposableBean
The org.springframework.beans.factory.InitializingBean interface allows a bean to perform initialization work after all necessary properties on the bean have been set by the container.
The InitializingBean
interface specifies a single method:
void afterPropertiesSet() throws Exception; |
This is not a preferrable way to initialize the bean because it tightly couple your bean class with spring container. A better approach is to use “init-method” attribute in bean definition in applicationContext.xml
file.
Similarly, implementing the org.springframework.beans.factory.DisposableBean interface allows a bean to get a callback when the container containing it is destroyed.
No comments:
Post a Comment