Search This Blog

Saturday, 21 April 2012

Custom Bean Initialization and Destroy Methods

It is possible that we may need to execute some initialization code when the bean has been initialized successfully by the Spring Container. We saw that the bean life cycle has several methods that can be used to initialize our bean.
Consider the Car class below.
public class CustomInitDestroyCar implements ICar {
    private Engine combustEngine;
    public CustomInitDestroyCar() {
        System.out.println("Creating object");

    public Engine getCombustEngine() {
        return combustEngine;

    public void setCombustEngine(Engine combustEngine) {
        System.out.println("Setting the properties");
        this.combustEngine = combustEngine;

    public void checkEngine() {
        System.out.println("Checking if engine is fine");
        // engine checkup code

    public void cleanCar() {
        System.out.println("Cleaning the car after use");
        // engine cleanup code

    public String describe() {
        return "Car in use " + this + ", engine is " + this.getCombustEngine();
  • Before the car is used by anybody, we would like to check the car Engine. 
  • Similarly after the car has been used successfully, the car needs to be cleaned. 
  • The code to clean the car cannot be called in the constructor as we need the engine property to be set. We also do not want to write this code in the setter method and then use flags to manage the same.
What would be an easy solution is to tell the Spring container to call the checkEngine() method when the bean is ready. Similarly the container will call the cleanCar() method when the car usage is complete( or the bean is ready for destruction). The XML configuration includes all the details.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""

    <bean id="car" class="" 
        init-method="checkEngine" destroy-method="cleanCar"    

    <bean id="combustEngine" class="" p:name="Combusto" />
On executing the below code:
public static void main(String[] args) {
    XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("init-destroy-beans.xml"));
    CustomInitDestroyCar car = (CustomInitDestroyCar) beanFactory.getBean("car");
The output is as below:
Creating object
Setting the properties
Checking if engine is fine
Car in use, engine is Engine - and name Combusto
Cleaning the car after use
As can be seen,
  1. the container created a new object and then went about setting its properties
  2. After complete configuration, it called the init method
  3. Similarly when we called the destroyBean() method of the container, it executed the custom destroy method before disposing of the bean.
In a later post we shall how to set these properties in a common manner for a host of beans.

No comments:

Post a Comment