top of page
vadhapriya

Bean life cycle in Java Spring

The bean life cycle refers to when & how the bean is instantiated, what action it performs until it lives, and when & how it is destroyed. In this blog, we will discuss the life cycle of the bean. 

Bean life cycle is managed by the spring container. When we run the program then, first of all, the spring container gets started. After that, the container creates the instance of a bean as per the request, and then dependencies are injected. And finally, the bean is destroyed when the spring container is closed. Therefore, if we want to execute some code on the bean instantiation and just after closing the spring container, then we can write that code inside the custom init() method and the destroy() method.


Below is the diagram of Bean life cycle flow.





Implement the life Cycle of the Bean using Annotation : 


To provide the facility to the created bean to invoke custom init() method on the startup of a spring container and to invoke the custom destroy() method on closing the container, we need to annotate init() method by @PostConstruct annotation and destroy() method by @PreDestroy annotation.


The following steps are followed:

  1. First , we need to create a bean HelloWorld.java in this case and annotate the custom init() method with @PostConstruct and destroy() method with @PreDestroy.




2. Now, we need to configure the spring XML file spring.xml and define the bean.




3. Finally, we need to create a driver class to run this bean.






5 views0 comments

Recent Posts

See All

Kommentarer


bottom of page