00:00

BeanPostProcessor in Spring

Last updated:

A BeanPostProcessor in Spring is a hook that sees every bean the container creates and may change it, or replace it with another object, before anyone else gets it. Much of Spring's "magic" is built this way: @Autowired, @PostConstruct, @Transactional, @Async and @Scheduled all work because a bean post-processor looks at your beans during startup and acts on what it finds.

This tutorial explains when the two post-processor methods run, which built-in processors you rely on every day, and how to write your own processor that adds execution-time logging to methods marked with a custom annotation. It also covers ordering, why processor beans should be declared static, the famous "not eligible for getting processed by all BeanPostProcessors" warning, and how to test a processor.

1. What Is a BeanPostProcessor?

BeanPostProcessor (org.springframework.beans.factory.config) is an interface with two default methods:

BeanPostProcessor.java (simplified)
public interface BeanPostProcessor {

    default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
}

Spring calls both methods for every bean it creates in the context, passing the bean instance and its name. Whatever object the method returns is used from then on. Returning the same bean means "no change"; returning a different object, typically a proxy that wraps the bean, replaces it for everyone who injects it.

Analogy: Picture a factory line where every finished product passes inspection stations before shipping. One station checks paperwork, another adds a protective case. The product designer never sees the stations, but every product leaves the factory with them applied. Bean post-processors are those stations.

2. When BeanPostProcessor Methods Run

Where bean post-processors act in a bean's lifecycleFor each bean, Spring instantiates it, injects its dependencies and calls Aware interfaces. Then every BeanPostProcessor's postProcessBeforeInitialization method runs, followed by the initialization callbacks such as afterPropertiesSet and the custom init method. Then every postProcessAfterInitialization method runs; this is where proxies are created. The object returned by the last processor is the bean other beans receive. Instantiate + inject + Aware postProcess- BeforeInitialization (every processor) Init callbacks afterPropertiesSet, init method postProcess- AfterInitialization (may return a proxy) Bean ready @PostConstruct itself runs inside the "before" step, through CommonAnnotationBeanPostProcessor.
"Before" runs ahead of the init callbacks; "after" runs once the bean is initialized and is where proxies are returned.
  • postProcessBeforeInitialization runs after dependencies are injected but before afterPropertiesSet() and custom init methods. Use it to inspect or configure the raw bean.
  • postProcessAfterInitialization runs after all initialization. Use it to wrap the bean in a proxy, because the bean is now complete.

The full sequence is described in the Spring bean lifecycle. Post-processors themselves are created early, before all other beans, so that they are ready when ordinary beans are created.

3. Built-In BeanPostProcessors You Already Use

ProcessorWhat it does
AutowiredAnnotationBeanPostProcessorInjects @Autowired and @Value fields and methods, and picks the constructor
CommonAnnotationBeanPostProcessorCalls @PostConstruct and @PreDestroy methods and handles @Resource
ApplicationContextAwareProcessorCalls ApplicationContextAware, EnvironmentAware and similar interfaces
Auto-proxy creators (AbstractAutoProxyCreator subclasses)Wrap beans in proxies for @Transactional, @Cacheable and @Aspect advice
AsyncAnnotationBeanPostProcessorProxies beans with @Async methods
ScheduledAnnotationBeanPostProcessorFinds @Scheduled methods and registers them with the scheduler
ConfigurationPropertiesBindingPostProcessorBinds @ConfigurationProperties beans to configuration values (Spring Boot)
PersistenceExceptionTranslationPostProcessorAdds exception translation to @Repository beans

This is also why the @Transactional pitfalls make sense: the proxy is created in postProcessAfterInitialization, so anything that runs earlier, or calls through this, never goes through it. The proxy mechanism itself is covered in AOP in Spring Boot.

4. A Complete Example: A @TrackTime Annotation

We want to annotate service methods with @TrackTime and have their execution time logged, without touching the services. A bean post-processor finds beans with such methods and returns a proxy that measures them.

4.1 The Annotation

TrackTime.java
package com.javabytechie.shop.monitoring;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TrackTime {
}

4.2 The BeanPostProcessor

TrackTimeBeanPostProcessor.java
package com.javabytechie.shop.monitoring;

import java.lang.reflect.Method;
import java.util.Arrays;
import org.aopalliance.intercept.MethodInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.annotation.AnnotatedElementUtils;

public class TrackTimeBeanPostProcessor implements BeanPostProcessor {

    private static final Logger log = LoggerFactory.getLogger(TrackTimeBeanPostProcessor.class);

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        Class<?> targetClass = AopUtils.getTargetClass(bean);
        boolean hasTrackedMethod = Arrays.stream(targetClass.getMethods())
                .anyMatch(method -> AnnotatedElementUtils.hasAnnotation(method, TrackTime.class));
        if (!hasTrackedMethod) {
            return bean;                       // most beans: unchanged
        }
        log.info("Adding execution-time tracking to bean '{}'", beanName);
        ProxyFactory factory = new ProxyFactory(bean);
        factory.setProxyTargetClass(true);     // keep the class type, so injection by class works
        factory.addAdvice((MethodInterceptor) invocation -> {
            Method method = AopUtils.getMostSpecificMethod(invocation.getMethod(), targetClass);
            if (!AnnotatedElementUtils.hasAnnotation(method, TrackTime.class)) {
                return invocation.proceed();
            }
            long start = System.nanoTime();
            try {
                return invocation.proceed();
            } finally {
                long millis = (System.nanoTime() - start) / 1_000_000;
                log.info("{}.{} took {} ms", targetClass.getSimpleName(), method.getName(), millis);
            }
        });
        return factory.getProxy();
    }
}

ProxyFactory is Spring AOP's programmatic way to build a proxy. With setProxyTargetClass(true) it creates a CGLIB subclass, so the proxy is still an instance of the original class.

4.3 A Service That Uses It

InvoiceService.java
package com.javabytechie.shop.billing;

import com.javabytechie.shop.monitoring.TrackTime;
import org.springframework.stereotype.Service;

@Service
public class InvoiceService {

    @TrackTime
    public String generate(String orderId) throws InterruptedException {
        Thread.sleep(150);   // stands in for rendering a PDF
        return "INV-" + orderId;
    }

    public String status(String invoiceId) {
        return invoiceId + ": SENT";
    }
}

4.4 Registration and a Demo Runner

MonitoringConfig.java
package com.javabytechie.shop.monitoring;

import com.javabytechie.shop.billing.InvoiceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
class MonitoringConfig {

    private static final Logger log = LoggerFactory.getLogger(MonitoringConfig.class);

    @Bean
    static TrackTimeBeanPostProcessor trackTimeBeanPostProcessor() {
        return new TrackTimeBeanPostProcessor();
    }

    @Bean
    ApplicationRunner invoiceDemo(InvoiceService invoices) {
        return args -> {
            String invoiceId = invoices.generate("ORD-3001");
            log.info("Status: {}", invoices.status(invoiceId));
        };
    }
}
Console
Adding execution-time tracking to bean 'invoiceService'
Started ShopApplication in 1.19 seconds (process running for 1.44)
InvoiceService.generate took 151 ms
Status: INV-ORD-3001: SENT

Only generate is timed; status passes straight through. InvoiceService knows nothing about timing, and any bean can opt in with the annotation.

In production: for this exact need, an @Aspect or Micrometer's @Timed and @Observed support is simpler and composes better with other proxies. The example shows the mechanism those features are built on.

5. Registering a BeanPostProcessor Correctly

An ApplicationContext detects any bean that implements BeanPostProcessor and registers it automatically, before creating ordinary beans. Two rules make registration safe:

  • Declare @Bean methods for processors as static. A non-static @Bean method needs an instance of its @Configuration class, so that class, and everything it injects, would be created early, before the other processors are ready. A static method needs no instance.
  • Keep the processor's own dependencies minimal. Every bean injected into a processor is created early too, and misses the processing other processors would have given it. If a dependency is needed, inject an ObjectProvider and resolve it lazily.

A processor annotated with @Component also works, as long as it has no heavy dependencies.

6. Ordering Several BeanPostProcessors

Spring registers processors in three groups: those implementing PriorityOrdered, then Ordered, then the rest. Within a group, a lower order value runs first. The order matters when processors wrap the same bean: the one that runs last in postProcessAfterInitialization produces the outermost proxy.

TrackTimeBeanPostProcessor.java (ordered)
public class TrackTimeBeanPostProcessor implements BeanPostProcessor, Ordered {

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE - 10;
    }
    // ...
}

7. Specialized BeanPostProcessor Interfaces

InterfaceExtra hookUsed by
InstantiationAwareBeanPostProcessorBefore and after instantiation, and when properties are appliedField and setter injection
SmartInstantiationAwareBeanPostProcessorChoose constructors, predict types, provide early references for cyclesConstructor selection, auto-proxying
MergedBeanDefinitionPostProcessorInspect the bean definition before properties are setCaching injection metadata
DestructionAwareBeanPostProcessorBefore a bean is destroyed@PreDestroy support

Application code rarely needs these. If you want to change bean definitions rather than bean instances, you need the other extension point: BeanFactoryPostProcessor.

8. Testing a BeanPostProcessor

Spring Boot's ApplicationContextRunner starts a small context with only the beans you list, which makes processor tests fast and precise. The test checks both sides: a bean without the annotation stays unwrapped, a bean with it becomes a proxy.

TrackTimeBeanPostProcessorTest.java
package com.javabytechie.shop.monitoring;

import static org.assertj.core.api.Assertions.assertThat;

import com.javabytechie.shop.billing.InvoiceService;
import org.junit.jupiter.api.Test;
import org.springframework.aop.support.AopUtils;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;

class TrackTimeBeanPostProcessorTest {

    static class PlainService {
        public String ping() {
            return "pong";
        }
    }

    private final ApplicationContextRunner runner = new ApplicationContextRunner()
            .withBean(InvoiceService.class)
            .withBean(PlainService.class);

    @Test
    void withoutTheProcessorNothingIsProxied() {
        runner.run(context ->
                assertThat(AopUtils.isAopProxy(context.getBean(InvoiceService.class))).isFalse());
    }

    @Test
    void withTheProcessorOnlyAnnotatedBeansAreProxied() {
        runner.withBean(TrackTimeBeanPostProcessor.class).run(context -> {
            InvoiceService invoices = context.getBean(InvoiceService.class);
            assertThat(AopUtils.isAopProxy(invoices)).isTrue();
            assertThat(AopUtils.isAopProxy(context.getBean(PlainService.class))).isFalse();
            assertThat(invoices.generate("ORD-1")).isEqualTo("INV-ORD-1");
        });
    }
}

9. Common Pitfalls

9.1 "Not Eligible for Getting Processed by All BeanPostProcessors"

Console
Bean 'auditRepository' of type [com.javabytechie.shop.audit.AuditRepository] is not eligible for getting
processed by all BeanPostProcessors (for example: not eligible for auto-proxying). ...

This warning means a bean was created before all processors were registered, usually because a processor, or the non-static configuration class that declares it, injects it. The bean then misses later processors, so its @Transactional or @Async annotations silently do nothing. Make the @Bean method static and remove or defer the processor's dependencies.

9.2 Returning null

Returning null from a post-processing method does not remove the bean; in current Spring versions it simply stops the processing chain for that bean. Return the original bean when you have nothing to do.

9.3 Proxy Type Surprises

An interface-based (JDK) proxy implements the bean's interfaces but is not an instance of its class. Injecting the bean by its class then fails with BeanNotOfRequiredTypeException. Use class-based proxies, as in the example, or inject by interface.

9.4 Expensive Checks for Every Bean

A processor runs for every bean, often hundreds, including Spring's own. Keep the "does this bean concern me?" check cheap, and return quickly.

10. When to Write One and When to Avoid It

Good reasonBetter alternative exists
A framework-style feature driven by your own annotation across many beansLogging or timing a few methods: use an @Aspect or Micrometer
Validating that beans of a type follow a rule at startupInitializing one bean: use @PostConstruct
Registering annotated methods with a registry, like @Scheduled doesChanging bean definitions or registering beans: use a BeanFactoryPostProcessor or BeanRegistrar

11. Best Practices

  • Declare processor @Bean methods as static.
  • Avoid injecting beans into processors; use ObjectProvider if you must.
  • Return the original bean unless you really need to change it.
  • Wrap beans only in postProcessAfterInitialization, when they are fully initialized.
  • Use class-based proxies when callers may inject the bean by its class.
  • Treat the "not eligible" warning as a bug and fix the early creation it reports.
  • Test with ApplicationContextRunner, checking both processed and unprocessed beans.

12. Summary

A BeanPostProcessor in Spring sees every bean the container creates, once before its initialization callbacks and once after, and can return a modified or wrapped object that replaces the bean. Spring builds injection, @PostConstruct, transactions, caching, @Async and @Scheduled on this mechanism, and you can use it for your own annotation-driven features, as the @TrackTime example shows. Declare processors in static @Bean methods, keep their dependencies minimal, create proxies only after initialization, and test them with ApplicationContextRunner; for simpler cases, an aspect is usually enough.

13. References