BeanPostProcessor

Basic Spring
≈ 2 min read

An extension point around bean initialization

Sometimes you need to apply common processing to many beans: validate them, collect metadata, modify them, or even replace an object before the application starts using it. For this, Spring provides the BeanPostProcessor interface.

@Component
class LoggingBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        System.out.println("Ready: " + beanName);
        return bean;
    }
}

Post-processor methods are called by the container for created beans around the initialization stage. In the example, we do not change anything: we simply print the name of a ready bean and return the same object.

Why the method returns an object

The contract allows returning not only the original bean but also another object. Part of Spring's internal magic is built on this idea: infrastructure can wrap a bean with additional behavior without forcing the class itself to know about that mechanism.

BeanPostProcessor is an infrastructure tool. In normal business logic, you rarely need to write your own post-processors. It is much more important to understand that Spring itself actively uses such extension points.

On the next pages, we will see two mechanisms where the idea of “adding behavior around a regular bean” is especially visible: AOP and proxies.