Managing Spring Bean Lifecycle Through Callback Methods

Spring container manages beans from instantiation to destruction, providing hooks for custom initialization and cleanup behavior. This mechanism ensures proper resource acquisition and release.

Create a demonstration component with lifecycle-aware methods:

package com.springdemo.components;

public class ResourceHandler {
    
    public void onInit() {
        System.out.println("ResourceHandler acquiring connections...");
    }
    
    public void handleRequest() {
        System.out.println("Processing business logic...");
    }
    
    public void onDestroy() {
        System.out.println("ResourceHandler releasing resources...");
    }
}

Configure the bean definition with lifecycle method references:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="resourceHandler" 
          class="com.springdemo.components.ResourceHandler"
          init-method="onInit"
          destroy-method="onDestroy"/>
</beans>

The init-method and destroy-method attributes map the container events to custom methods in the bean class.

Trigger the lifecycle with an application bootstrap class:

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Bootstrap {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext springContext = 
            new ClassPathXmlApplicationContext("beans.xml");
        
        ResourceHandler handler = springContext.getBean("resourceHandler", ResourceHandler.class);
        handler.handleRequest();
        
        springContext.close();
    }
}

Executing this program produces the following sequence:

ResourceHandler acquiring connections...
Processing business logic...
ResourceHandler releasing resources...

The container invokes onInit() after instantiating the bean and satisfying dependencies. When close() executes, it triggers onDestroy() before bean removal, enabling graceful shutdown procedures.

Tags: Spring bean-lifecycle dependency-injection java spring-framework

Posted on Thu, 25 Jun 2026 16:20:06 +0000 by NoobPHP