Spring init-method and destroy-method example

In this post, we will see about Spring init-method and destroy-method.
When bean is instantiated or destroyed , there are some operations you may need to perform, so you can use init-method and destroy-method to call this methods while bean is being created or destroyed.
Lets understand it with the help of simple example:
For configuring spring in your eclipse ide please refer  hello world example

1.Country.java:

This is simple pojo class which have only one attribute as countryName.
Create Country.java under package org.arpit.java2blog.Copy following content into Country.java.
package org.arpit.java2blog;

public class Country {

 String countryName ;

 public String getCountryName() {
  return countryName;
 }

 public void setCountryName(String countryName) {
  this.countryName = countryName;
 }

 public void init()
 {
  System.out.println("In init block of country");
 }

 public void destroy()
 {
  System.out.println("In destroy block of country");
 }
}

2.SpringInitDestroyMain.java

This class contains main function.Create SpringInitDestroyMain.java under package org.arpit.java2blog.Copy following content into SpringInitDestroyMain.java
package org.arpit.java2blog;

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

public class SpringInitDestroyMain{

 public static void main(String[] args) {

  AbstractApplicationContext appContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");
  Country countryObj = (Country) appContext.getBean("country");
  System.out.println("Country Name: "+countryObj.getCountryName());
  appContext.registerShutdownHook();
 }
}

Here you need to register a shutdown hook registerShutdownHook() method that is declared on the AbstractApplicationContext class. This will ensures a graceful shutdown and calls the relevant destroy methods.

3.ApplicationContext.xml




 
 
 

4.Run it

When you will run above application,you will get following as output.
In init block of country
Country Name: India
In destroy block of country

Default Initialization and destroy method:

If you want to put default methods for all beans and do not want to configure of individual beans, you can use default-init-method and default-destroy-method  with tag, so it will call init and destroy methods for all beans configured in ApplicationContext.xml.



 
 
 

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.