Sub topic 8
Customizing every bean with BeanPostProcessor
This chapter assumes you know the init callbacks from the previous chapters (@PostConstruct, afterPropertiesSet) and can run a Spring application.
What a BeanPostProcessor does
A BeanPostProcessor is a container-level hook. You register it as a bean, and Spring calls it for every other bean it creates. An init callback belongs to one class and runs on that class's own instance. A post-processor sits outside the beans and can inspect or replace any of them.
The interface has two methods, both with default implementations:
postProcessBeforeInitialization(bean, beanName)runs after the bean is instantiated and its dependencies are injected, but before its init callbacks.postProcessAfterInitialization(bean, beanName)runs after all init callbacks have finished.
Both methods return the bean that the container should use from then on.
A logging example
This post-processor reports on DemoBean from the lifecycle example. It ignores every other bean and returns it unchanged.
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 DemoBean in the same context, startup prints:
constructor
before initialization: demoBean
@PostConstruct
afterPropertiesSet
after initialization: demoBeanReplacing the bean
The returned object does not have to be the one you received. Spring uses whatever you return, so a post-processor can wrap a bean in a proxy. Spring's own features work this way. @PostConstruct is handled by a built-in post-processor in its before-initialization step. AOP proxies, which power @Transactional and @Async, are created in the after-initialization step. They are created there so that the proxy wraps a fully initialized bean.
Common errors
- Returning null. Return the bean, even when you change nothing. Returning
nullstops the remaining post-processors from running for that bean. - Expecting full processing of early dependencies. Spring creates post-processors before ordinary beans. Any bean a post-processor depends on is created early, so some post-processors never see it. Spring logs "not eligible for getting processed by all BeanPostProcessors" in this case.
- Non-static
@Beanmethods. If you declare a post-processor with@Bean, make the methodstatic. Otherwise Spring must instantiate the whole configuration class early, which can disable@Autowiredand@PostConstructon it. - Wrong ordering. If you have several post-processors, implement
OrderedorPriorityOrdered. Without an order, you cannot rely on the sequence. - Slow code. The methods run for every bean, so keep them fast and filter early with
instanceofor an annotation check.
Exercise
You write a BeanPostProcessor that wraps a bean in a proxy. Should the wrapping happen in the before-initialization method or the after-initialization method, and why?
Show answer
In the after-initialization method. At that point the init callbacks have already run on the real bean, so the proxy wraps a fully initialized object. This is also where Spring creates its own AOP proxies.