BeanPostProcessor in Spring
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:
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.
2. When BeanPostProcessor Methods Run
postProcessBeforeInitializationruns after dependencies are injected but beforeafterPropertiesSet()and custom init methods. Use it to inspect or configure the raw bean.postProcessAfterInitializationruns 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
| Processor | What it does |
|---|---|
AutowiredAnnotationBeanPostProcessor | Injects @Autowired and @Value fields and methods, and picks the constructor |
CommonAnnotationBeanPostProcessor | Calls @PostConstruct and @PreDestroy methods and handles @Resource |
ApplicationContextAwareProcessor | Calls ApplicationContextAware, EnvironmentAware and similar interfaces |
Auto-proxy creators (AbstractAutoProxyCreator subclasses) | Wrap beans in proxies for @Transactional, @Cacheable and @Aspect advice |
AsyncAnnotationBeanPostProcessor | Proxies beans with @Async methods |
ScheduledAnnotationBeanPostProcessor | Finds @Scheduled methods and registers them with the scheduler |
ConfigurationPropertiesBindingPostProcessor | Binds @ConfigurationProperties beans to configuration values (Spring Boot) |
PersistenceExceptionTranslationPostProcessor | Adds 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
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
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
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
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));
};
}
}
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.
@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
@Beanmethods for processors asstatic. A non-static@Beanmethod needs an instance of its@Configurationclass, so that class, and everything it injects, would be created early, before the other processors are ready. Astaticmethod 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
ObjectProviderand 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.
public class TrackTimeBeanPostProcessor implements BeanPostProcessor, Ordered {
@Override
public int getOrder() {
return Ordered.LOWEST_PRECEDENCE - 10;
}
// ...
}
7. Specialized BeanPostProcessor Interfaces
| Interface | Extra hook | Used by |
|---|---|---|
InstantiationAwareBeanPostProcessor | Before and after instantiation, and when properties are applied | Field and setter injection |
SmartInstantiationAwareBeanPostProcessor | Choose constructors, predict types, provide early references for cycles | Constructor selection, auto-proxying |
MergedBeanDefinitionPostProcessor | Inspect the bean definition before properties are set | Caching injection metadata |
DestructionAwareBeanPostProcessor | Before 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.
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"
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 reason | Better alternative exists |
|---|---|
| A framework-style feature driven by your own annotation across many beans | Logging or timing a few methods: use an @Aspect or Micrometer |
| Validating that beans of a type follow a rule at startup | Initializing one bean: use @PostConstruct |
Registering annotated methods with a registry, like @Scheduled does | Changing bean definitions or registering beans: use a BeanFactoryPostProcessor or BeanRegistrar |
11. Best Practices
- Declare processor
@Beanmethods asstatic. - Avoid injecting beans into processors; use
ObjectProviderif 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
BeanPostProcessor in Spring Interview Questions and Answers
Common interview questions on BeanPostProcessor in Spring, from basic to scenario-based, with short answers you can explain in your own words.
Q. What is a BeanPostProcessor, and when are its two methods called?
Answer: It is a container extension point that receives every bean instance the context creates. postProcessBeforeInitialization runs after dependency injection and Aware callbacks but before afterPropertiesSet() and custom init methods; postProcessAfterInitialization runs after them. Each method returns the object to use, so a processor can replace the bean, typically with a proxy.
Q. Which common Spring features are implemented with BeanPostProcessors?
Answer: @Autowired and @Value injection (AutowiredAnnotationBeanPostProcessor), @PostConstruct and @PreDestroy (CommonAnnotationBeanPostProcessor), Aware interfaces, @Transactional, @Cacheable and aspects (auto-proxy creators), @Async, @Scheduled, Spring Boot's @ConfigurationProperties binding, and exception translation for @Repository beans.
Q. Why should a @Bean method that returns a BeanPostProcessor be static?
Answer: Processors are created before ordinary beans. A non-static @Bean method needs its @Configuration instance, so the configuration class and all its injected dependencies would be created early, before other processors are registered, and would miss their processing. A static method lets Spring call the factory method without creating the configuration instance.
Q. What does the warning "is not eligible for getting processed by all BeanPostProcessors" mean?
Answer: The named bean was created while processors were still being registered, usually because a processor or its non-static configuration class depends on it. It therefore skipped some processors, often the auto-proxy creator, so annotations such as @Transactional or @Async on it may not work. Fix it by making processor @Bean methods static and removing or deferring their dependencies.
Q. How do you control the order in which several BeanPostProcessors run?
Answer: Implement PriorityOrdered or Ordered. Spring registers PriorityOrdered processors first, then Ordered ones, then all others, and sorts within each group by order value, lowest first. When several processors wrap the same bean, the one applied last in postProcessAfterInitialization creates the outermost proxy.
Q. After adding a custom BeanPostProcessor that returns a JDK proxy, startup fails with BeanNotOfRequiredTypeException. Why?
Answer: A JDK dynamic proxy implements only the bean's interfaces; it is not an instance of the bean's class. Any injection point declared with the concrete class can no longer accept it. Create a class-based proxy, for example with ProxyFactory.setProxyTargetClass(true), or change consumers to depend on the interface.