Spring Bean Life Cycle

The Spring bean life cycle has two init and destroy methods.

The init method will get called just after the initialization of bean properties to manipulate data.

The destroy method gets called when a bean is no longer required and the object is ready to decompose. This method is used as a cleanup activity.

Create Person.java class with init() and destroy() method as shown below.

Create a bean tag element as mentioned below at line number 8. Declare the init-method and destroy-method attributes’ values as init and destroy, respectively, as defined in the Person.java class.

Create an instance of Person class using ClassPathXmlApplicationContext class at line number 12.

Run above DemoApplication.java will show below output.

OUTPUT:
init() method called
Print name
destroy() method called

If we have multiple classes that have init and destroy methods defined.

We can define default-init-method and default-destroy-method for all beans at once, as shown below, in place of writing init-method and destroy-method for every bean tag element.

Imran Khan

Specialist Master (Architect) with a passion for cutting-edge technologies like AEM (Adobe Experience Manager) and a proven track record of delivering high-quality software solutions.

  • Languages: Java, Python
  • Frameworks: J2EE, Spring, Struts 2.0, Hibernate
  • Web Technologies: React, HTML, CSS
  • Analytics: Adobe Analytics
  • Tools & Technologies: IntelliJ, JIRA

🌐 LinkedIn

📝 Blogs

📧 Imran Khan