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.

2.SpringInitDestroyMain.java

This class contains main function.Create SpringInitDestroyMain.java under package org.arpit.java2blog.Copy following content into SpringInitDestroyMain.java
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.

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.

Was this post helpful?

Leave a Reply

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