Spring Bean Post Processor example

๐ŸŒฑ Understanding BeanPostProcessor in Spring Framework — with Example

In Spring, the BeanPostProcessor interface allows developers to hook into the bean lifecycle and perform custom actions before and after bean initialization.

It’s a powerful extension point that lets you modify bean instances or inject additional behavior after Spring has created and configured them — without changing the original bean code.


⚙️ What Is a BeanPostProcessor?

A BeanPostProcessor defines callback methods that are automatically invoked by the Spring container during bean creation.

It provides two key methods:

MethodDescription
postProcessBeforeInitialization(Object bean, String beanName)Called before the bean’s initialization callback (@PostConstruct, afterPropertiesSet(), etc.)
postProcessAfterInitialization(Object bean, String beanName)Called after the bean’s initialization is complete

With this, you can:

  • Inject custom logic before or after a bean is initialized.

  • Implement cross-cutting concerns like logging, metrics, auditing, or validation.

  • Wrap or modify bean instances dynamically.


๐Ÿงฉ Example — Custom BeanPostProcessor in Spring

In this example, we’ll:

  1. Define a simple Student bean.

  2. Create a MyBeanPostProcessor class.

  3. Configure both in Spring XML.

  4. Observe how the bean lifecycle is intercepted by our post-processor.


๐Ÿงฑ 1. Spring XML Configuration (spring-core.xml)

<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-2.5.xsd"> <!-- Define the Student bean --> <bean id="studentBean" class="com.vinod.test.Student" scope="singleton" /> <!-- Register the custom BeanPostProcessor --> <bean class="com.vinod.test.MyBeanPostProcessor" /> </beans>

๐Ÿง  2. Implementing the BeanPostProcessor

package com.vinod.test; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; /** * Custom BeanPostProcessor to intercept bean initialization events. * * This class demonstrates how Spring allows developers to add * custom behavior before and after a bean is initialized. * * @author vinod */ public class MyBeanPostProcessor implements BeanPostProcessor { @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { System.out.println("Before Initialization : " + beanName); return bean; // you can return a proxy or modified bean here } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { System.out.println("After Initialization : " + beanName); return bean; } }

๐Ÿ‘ฉ‍๐ŸŽ“ 3. The Bean Class — Student.java

package com.vinod.test; public class Student { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }

๐Ÿš€ 4. Test Class — SpringCoreScopeTest.java

package com.vinod.test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Loads Spring context and retrieves a bean to demonstrate * BeanPostProcessor execution order. */ public class SpringCoreScopeTest { public static void main(String[] args) { // Load Spring context from XML configuration ApplicationContext context = new ClassPathXmlApplicationContext("spring-core.xml"); // Retrieve the Student bean Student student = (Student) context.getBean("studentBean"); student.setName("Vinod"); // Display the bean value System.out.println(student.getName()); } }

๐Ÿงพ 5. Output

Before Initialization : studentBean After Initialization : studentBean Vinod

๐Ÿ” How It Works — Step by Step

  1. The Spring container loads the XML configuration.

  2. It creates the studentBean instance.

  3. Before calling any initialization methods, Spring invokes
    postProcessBeforeInitialization() — printing "Before Initialization : studentBean".

  4. After the bean is initialized, Spring calls
    postProcessAfterInitialization() — printing "After Initialization : studentBean".

  5. The bean is then available for use in the application context.


๐Ÿง  When to Use BeanPostProcessor

You can use BeanPostProcessor to:

  • Inject custom logging or tracing.

  • Automatically wrap beans with proxies (e.g., AOP-style logic).

  • Perform validation or custom initialization.

  • Modify beans dynamically (for example, adding extra configuration).


๐Ÿงฑ Example Visualization

Spring Container │ ▼ [Bean Instantiation] │ ▼ → postProcessBeforeInitialization() │ ▼ [Bean Initialization] │ ▼ → postProcessAfterInitialization() │ ▼ [Bean Ready for Use]

⚡ Key Takeaways

ConceptDescription
InterfaceBeanPostProcessor (from org.springframework.beans.factory.config)
PurposeIntercept bean creation and apply custom logic
MethodspostProcessBeforeInitialization() and postProcessAfterInitialization()
Return TypeYou can return the same or a modified bean
ScopeApplies to all beans managed by the container

No comments:

Post a Comment

Model Context Protocol (MCP) — Complete Guide for Backend Engineers

  Model Context Protocol (MCP) — Complete Guide for Backend Engineers Build Tools, Resources, and AI-Driven Services Using LangChain Moder...

Featured Posts