What is the Spring bean life cycle?
We have already seen what spring bean is and how to create it. Now we will see what is Spring bean life cycle.
In the previous blog, Spring Beans we have already seen that The Spring IoC container is responsible for instantiating, initializing, and wiring beans. The container also manages the life cycle of beans.
When we run the program the spring container gets started first then the container creates the instance of a bean as per the request, after that dependencies are injected. Finally, the bean is destroyed when the spring container is closed.
If we want to execute some code on the bean instantiation just after closing the spring container, then we can write that code inside the custom init() method and the destroy() method respectively.
The following image shows the lifecycle of the bean
we can implement the bean lifecycle in three ways as follows:
- By XML configuration
- By Programmatic approach
- By Using Annotations
We will see each approach in detail below
- XML configuration
- In this approach, we have created custom init() and destroy() methods in our class as shown below.
- The init method executes automatically when the bean is instantiated
- The destroy method executes when the spring container is closed.
- To avail of these two methods we need to register them in XML configuration while creating a bean as shown below.
- By Programmatic approach
- For this we need to implement two interfaces InitializingBean and DisposableBean and need to override afterPropertiesSet() and destroy() methods for init and destroy respectively.
- The afterPropertiesSet() method is invoked as the container starts and the bean is instantiated whereas, the destroy() method is invoked just after the container is closed.
- following is the example for our bean class
- To invoke the destroy method we have to call a close() method of ConfigurableApplicationContext.
- Now, we need to configure the spring XML file spring.xml and define the bean as shown below.
- By Using Annotations
- we can also use annotations @PostConstruct and @PreDestroy to invoke init() and destroy() methods respectively as shown in the below bean class.