Sub topic 8
Customizing every bean with BeanPostProcessor
This chapter assumes you know how a bean is instantiated and injected, and that you have seen @PostConstruct and afterPropertiesSet run. It covers the one hook that sees every bean the container creates.
What a BeanPostProcessor is
A BeanPostProcessor is a bean that the container calls for every other bean it creates. The interface has two methods, both with default implementations that return the bean unchanged:
postProcessBeforeInitialization(Object bean, String beanName)runs after the bean is instantiated and its dependencies are injected, before its initialization callbacks.postProcessAfterInitialization(Object bean, String beanName)runs after the initialization callbacks have finished.
Both methods return an object, and the container uses that returned object from then on. Usually you return the same bean you received. You may also return a different object, such as a wrapper or a proxy. This is how Spring implements much of its own behavior.
A processor is not limited to beans of one type. It receives each bean in the context, so you must filter by type, name, or annotation and return everything else untouched.
A minimal processor
This processor logs when DemoBean passes through each phase.
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
@Component
public class LoggingPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof DemoBean) {
System.out.println("before initialization: " + beanName);
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof DemoBean) {
System.out.println("after initialization: " + beanName);
}
return bean;
}
}With the DemoBean from the earlier chapter, the output is:
constructor
@PostConstruct
before initialization: demoBean
afterPropertiesSet
after initialization: demoBeanThe "before" line appears after @PostConstruct, which surprises many people. The reason is that @PostConstruct is not handled by the core container. It is handled by another BeanPostProcessor, Spring's CommonAnnotationBeanPostProcessor, in its "before initialization" step. That built-in processor implements PriorityOrdered, so it runs ahead of an unordered processor like yours.
The same mechanism handles @Autowired injection and Aware callbacks such as ApplicationContextAware. Several of the features you already use are post-processors.
Replacing a bean with a proxy
Returning a different object from postProcessAfterInitialization is the most powerful use of the interface. The next example wraps beans in a JDK dynamic proxy that logs how long each method call takes. To keep it small, it only handles beans whose name starts with timed and that implement an interface.
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Proxy;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
interface Greeter {
String greet(String name);
}
@Component("timedGreeter")
class SimpleGreeter implements Greeter {
@Override
public String greet(String name) {
return "Hello, " + name;
}
}
@Component
class TimingPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
Class<?>[] interfaces = bean.getClass().getInterfaces();
if (!beanName.startsWith("timed") || interfaces.length == 0) {
return bean;
}
return Proxy.newProxyInstance(bean.getClass().getClassLoader(), interfaces, (proxy, method, args) -> {
long start = System.nanoTime();
try {
return method.invoke(bean, args);
} catch (InvocationTargetException e) {
throw e.getCause();
} finally {
System.out.println(beanName + "." + method.getName() + " took "
+ (System.nanoTime() - start) / 1_000 + " µs");
}
});
}
}Other beans now receive the proxy when they ask for timedGreeter. The proxy is a Greeter but not a SimpleGreeter, so a field of type SimpleGreeter fails to inject. Inject the interface instead.
Spring's own proxying works the same way. @Transactional, @Async, and Spring AOP advice are applied by post-processors that return proxies. They use CGLIB when the bean has no interface.
BeanPostProcessor versus an init callback
| Row | Init callback (`@PostConstruct`, `initMethod`) | `BeanPostProcessor` |
|---|---|---|
| Declared on | The bean itself | A separate bean |
| Applies to | That one bean | Every bean in the container |
| Can replace the bean | No | Yes, by returning another object |
| Typical use | Prepare this bean's own state | Cross-cutting behavior: proxies, validation, registration |
If the logic concerns one class's own state, use an init callback. If the logic applies to many beans or must change what other beans receive, write a processor.
Ordering
The container registers processors in this order:
- Processors that implement
PriorityOrdered, sorted by their order value. - Processors that implement
Ordered, sorted by their order value. - All remaining processors, in registration order.
Each bean passes through the processors in that sequence for the "before" step. The "after" step uses the same sequence. If your processor must see the original bean before a proxy-creating processor wraps it, or must run on the proxy afterward, give it an explicit order:
import org.springframework.core.Ordered;
@Component
class FirstProcessor implements BeanPostProcessor, Ordered {
@Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE;
}
}@Order on a processor class does not affect registration order. The container only reads Ordered and PriorityOrdered here.
Common errors
Declaring a processor in a configuration class
A BeanPostProcessor must exist before the ordinary beans so it can process them. If you declare one with a regular @Bean method, the container must first instantiate the enclosing @Configuration class. That forces the configuration class to be created early, before any processor is ready, and Spring logs a message like this:
Bean 'processorConfig' of type [ProcessorConfig] is not eligible for getting processed by all BeanPostProcessorsDeclare the method static so the configuration instance is not needed:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ProcessorConfig {
@Bean
static LoggingPostProcessor loggingPostProcessor() {
return new LoggingPostProcessor();
}
}If you use this form, remove @Component from LoggingPostProcessor, or the processor is registered twice.
Injecting dependencies into a processor
A processor is created before ordinary beans. Any bean you inject into it is also created early, and the processors registered later never see that bean. Those beans are not proxied, for example, so @Transactional or @Async silently does nothing on them. Keep processors free of dependencies, or inject only what they truly need.
Returning null
Returning null from either method makes the container stop applying later processors to that bean. In current Spring versions it also leaves you with a broken bean. Always return the bean or a replacement.
Ignoring FactoryBean and prototype beans
Processors run for prototype beans each time one is created, so keep them cheap. For a FactoryBean, they run on the factory and on the product it creates. Check bean instanceof carefully if you only want one of them.
Expecting destruction hooks
BeanPostProcessor only covers creation. For a hook that runs before destruction, implement DestructionAwareBeanPostProcessor. It adds postProcessBeforeDestruction, which @PreDestroy handling itself relies on.
Running the example
You can watch all of this in a plain Java program. Closing the context also triggers the destruction callbacks.
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan
class AppConfig {
}
public class Main {
public static void main(String[] args) {
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class)) {
ctx.getBean(DemoBean.class);
System.out.println("context running");
}
}
}Exercise
A custom BeanPostProcessor with no ordering prints a line in postProcessBeforeInitialization. The bean it processes has a @PostConstruct method that also prints a line. Which line appears first, and why? What must you change so that the processor's line appears first?
Show answer
The @PostConstruct line appears first. @PostConstruct is handled by CommonAnnotationBeanPostProcessor, which is a PriorityOrdered BeanPostProcessor and therefore runs before unordered processors. To run first, make your processor implement PriorityOrdered with a getOrder() value lower than the built-in processor's order, which is Ordered.LOWESTPRECEDENCE - 3. Ordered.HIGHESTPRECEDENCE works. Implementing only Ordered is not enough, because all PriorityOrdered processors are registered before any Ordered one.