tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Spring > Core > Disposable Bean

Disposable Bean 

Spring Inversion of Control (IoC) also known as Dependency Injection (DI) is a process by which objects define their dependencies with collaborating objects. Spring provides DisposableBean interface which allows us to perform pre processing tasks when the container containing this bean is destroyed.  
package org.springframework.beans.factory;

public abstract interface DisposableBean
  public abstract void destroy() throws Exception;
File Name  :  

File Name  :  
package com.bethecoder.tutorials.spring3.basic;

import org.springframework.beans.factory.DisposableBean;

public class SimpleDisposableBean implements DisposableBean {

  private String simpleProp;

  public String getSimpleProp() {
    return simpleProp;

  public void setSimpleProp(String simpleProp) {
    this.simpleProp = simpleProp;

  public void destroy() throws Exception {

    System.out.println("In destroy callback : " + simpleProp);
    simpleProp = null
    System.out.println("In destroy callback : " + simpleProp);
  public String toString() {
    return "SimpleDisposableBean[" + simpleProp + "]";

File Name  :  
Author  :  Sudhakar KV
Email  :  [email protected]
package com.bethecoder.tutorials.spring3.tests.callbacks;

import org.springframework.context.ApplicationContext;

import com.bethecoder.tutorials.spring3.basic.SimpleDisposableBean;

public class DestructionCallback {

   @param args
  public static void main(String[] args) {
    System.out.println("Initializing ApplicationContext");
    ApplicationContext factory = new ClassPathXmlApplicationContext("destroy.xml");
    System.out.println("ApplicationContext Initialized");
    System.out.println("Accessing first bean");
    SimpleDisposableBean first = (SimpleDisposableBeanfactory.getBean("first");

    System.out.println("Accessing second bean");
    SimpleDisposableBean second = (SimpleDisposableBeanfactory.getBean("second");
     * Register a Shutdown hook for graceful Shutdown.
     * Calls the relevant destroy methods on your singleton beans 
     * so that all resources are released
    AbstractApplicationContext abc = (AbstractApplicationContext factory;


It gives the following output,
Initializing ApplicationContext
ApplicationContext Initialized

Accessing first bean

Accessing second bean

In destroy callback : SECOND
In destroy callback : null

In destroy callback : FIRST
In destroy callback : null


bl  br