Spring init-method and destroy-method example - Java @ Desk

Thursday, December 26, 2013

Spring init-method and destroy-method example

Spring init-method and destroy-method example

A bean configured in spring configuration file gets initialized when the file gets loaded in the spring container. There may arise a case where something needs to be initialized on bean initialization or needs to be destroyed before the bean nullifies.

Consider an example, the Properties file need to be loaded as soon as bean gets initialized. What happens to this property file when the bean gets destroyed. The best practice is to clear this property file. Also if the property file gets loaded on first client request, it would take additional time for the first request.

To achieve this, a bean need to be configured in a spring configuration file and following attributes are used for the bean:
1) init-method - Provide the method name of the bean declared which needs to get called once the bean is initialized. For example, loading of properties file.
2) destroy-method - Provide the method name of the bean declared which needs to get called once the bean is destroyed. For example, clearing properties file.

In case, a method name used with init-method or destory-method is not found in a class, it throws the following exception:
Error creating bean with name 'springInitDestroy'
defined in class path resource [com//spring//appContext.xml]:
Invalid destruction signature; nested exception is org.springframework.beans.factory.support.BeanDefinitionValidationException:
Couldn't find a destroy method named 'cleanUp1' on bean with name 'springInitDestroy'
Where cleanUp1 -> method name not found in class.

Below is the sample implementation:
1) Spring Configuration File:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"

 <context:annotation-config />

 <bean id="springInitDestroy" class="com.spring.SpringInitDestroy"
  init-method="initIt" destroy-method="cleanUp">


2) Spring Bean Class:
package com.spring;

public class SpringInitDestroy {

 public void initIt() throws Exception {
  System.out.println("Init method called on bean initialization");

 public void cleanUp() throws Exception {
  System.out.println("Destroy method called on bean destroy");

3) Test Client Class:

package com.spring;

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

public class SprintInitDestroyTest {
 public static void main(String[] args) {
  ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(
    new String[] { "com//spring//appContext.xml" });

  SpringInitDestroy initDestroy = (SpringInitDestroy) context

  System.out.println("Bean Created : " + initDestroy);


No comments:

Post a Comment