Spring callback methods example

Callback method:

A callback method in java is a method which is called when an event occurs. Normally we can implement that by passing an implementation of a certain interface to the system which is responsible for triggering the event.

Commonly used callback methods in spring:

Post-initialization callback methods:

Using InitializingBean interface:

The InitializingBean interface provides afterPropertiesSet() method which can be used for any post-initialization task.

Syntax:

public class TestBean implements InitializingBean {
   public void afterPropertiesSet() {
      // post-initialization task.
   }
}

Using init-method attribute:

In XML configuration metadata we can specify the name of the method which has a void no-argument signature in init-method attribute for any post-initialization task.

Syntax:

<bean id="testBean" class="Test" init-method="init"/>
In class definition:
public class Test {
   public void init() {
      // post-initialization task.
   }
}

Pre-destroy callback methods:

Using DisposableBean interface:

The DisposableBean interface provides destroy() method which can be used for any pre-destroy task.

Syntax:

public class TestBean implements DisposableBean {
   public void destroy() {
      // pre-destroy task.
   }
}

Using destroy-method attribute:

In XML configuration metadata we can specify the name of the method which has a void no-argument signature in destroy-method attribute for any pre-destroy task.

Syntax:

<bean id="testBean" class="Test" destroy-method=" destroy"/>
In class definition:
public class Test {
   public void destroy() {
      // pre-destroy task.
   }
}