Spring: Bean Lifecycle

Deepak jha
2 min readDec 27, 2020

In this blog, I will share my knowledge about the bean lifestyle, as we already discuss beans and their scope in my last blog, so I hope you now have a basic idea about the spring bean.

So, when the spring container starts there are few things happen, First Bean instantiated then the dependency injected, and then some spring internal processing occurs with the bean factory, and next, we have the option to write our own initialization code and after this point, Bean is ready for use in our application and at some point container will shut down.

I created this diagram to better understand the lifestyle of beans and also we will take a look at Init and Destroy method/hook.

Bean LifeCycle Method/Hooks

With the help of the bean lifecycle method, we can write our business logic or any custom code like bootstrapping data during bean initialization, also we can do the same thing while destruction of bean-like cleaning up the resources.

Bean-Lifecycle by XML configuration

When we use XML configuration for defining the bean, we have to use init-method and destroy-method attribute to define which method will call when the bean is instantiated and destroy.

Example :

In the web.xml configuration file, I created a bean name videoStreamingService and provided two attributes init-method and destroy-method and which will call the doSomeTaskOnInit when the bean is instantiated and doSomeTaskOnDestroy when the bean destroy.

Provided the web.xml to the spring Ioc container and shut down the container.

Output

Bean-Lifecycle by Spring’s Interfaces

We can implement Spring’s InitializingBean interface to run custom operations in afterPropertiesSet() phase:

output

Bean-Lifecycle by Spring’s Annotations

--

--