Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




Spring - Bean Lifecycle Methods

Bean Lifecycle Methods are the methods which executes before bean is created and after the bean is destroyed.

Let us understand with the below example :


Car Class

class Car {

  String brand;

  public void beanInitialize(){

    System.out.println("Car Initialized");
  }

  public void beanDestroy(){

    System.out.println("Car Destroyed");
  }

  // -- Getters and Setters --
}


We have put two methods 'public void beanInitialize()' and 'public void beanDestroy()'. We will have to put these method names in the <bean ..> property of 'Car'.

Let us see below :


application-context.xml

<?xml version = "1.0" encoding = "UTF-8"? >

<beans xmlns = "http://www.springframework.org/schema/beans"
  xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation = "http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd" >

  <bean name = "car" class = "Car" init-method="beanInitialize" destroy-method="beanDestroy" >
    <property name = "brand" value="Honda"/ >
   </bean >

</beans >


As mentioned above, there is an 'init-method' and a 'destroy-method' provided by Spring. All we have done is taken the 'beanInitialize()' and 'beanDestroy()' from the 'Car' class and initialized to it.


<bean name = "car" class = "Car" init-method="beanInitialize" destroy-method="beanDestroy" >

And Spring knows which method to call before the creation and destruction of a bean.

Before writing the main class let us keep two points in mind :


- We need to use AbstractApplicationContext instead of ApplicationContext.

- Register a shutDownHook for the application to shutdown.

Now, let us write the main application :


import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class FirstSpringApp {
  public static void main(String[] args) {

  AbstractApplicationContext applicationContext =
           new ClassPathXmlApplicationContext("application-context.xml");

  Car car = (Car)applicationContext.getBean("car");

  System.out.println("The value is : "+car.getBrand());

  applicationContext.registerShutdownHook();

}

Output :


  Car Initialized
   The value is : Honda
   Car Destroyed

If you look at the output message. The initialize method is called first and then the value of the 'Car' bean is displayed and finally the destroy method is called.

Next, we have registered a shutdown hook for the application to shutdown.


applicationContext.registerShutdownHook();

And used


AbstractApplicationContext applicationContext

Instead of ApplicationContext.