top of page

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.


ree



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.


ree


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


ree


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


ree




 
 
 

Recent Posts

See All

Comments


MiIT Logo

Company

Contact Us

905-487-4880 

5160 Explorer Dr #34, Mississauga,ON L4W 4T7

646-713-5711

4466 Buttonwood Ln Lilburn, GA 30047

262 Chapman Rd, STE 240 Newark DE 19702

Stay up to date on the latest from MiIT

  • Instagram
  • Facebook
  • http://linkedin.com/company/miittechnologies/about/
  • Whatsapp

© All Content MiIT Technologies Inc.2019 - 2025. All rights reserved.

bottom of page