Video in progress

Strong Middle 🌱 Spring

What is a BeanPostProcessor, and where does Spring itself use it?

A BeanPostProcessor is a hook into every bean after it is created: it is called before and after init. Spring uses it for @Autowired, @PostConstruct, @Async, the @Transactional proxies and validation.

📖 Answer

The interface:

public interface BeanPostProcessor {
    default Object postProcessBeforeInitialization(Object bean, String name) { return bean; }
    default Object postProcessAfterInitialization(Object bean, String name) { return bean; }
}

The main trick is that postProcessAfterInitialization can return a different object instead of the bean, namely a proxy. That's how Spring AOP works: the context holds not the real OrderService but the proxy wrapped around it.

Inside Spring:

  • AutowiredAnnotationBeanPostProcessor: @Autowired, @Value;
  • CommonAnnotationBeanPostProcessor: @PostConstruct, @PreDestroy;
  • AnnotationAwareAspectJAutoProxyCreator: proxies for @Transactional, @Cacheable and aspects;
  • AsyncAnnotationBeanPostProcessor: @Async.

You can write your own too, for example to collect beans that carry a certain annotation. But a BPP is created very early. If it depends on ordinary services, those services are also created early and skip the other post-processors, and the log says "is not eligible for getting processed by all BeanPostProcessors". As a result, @Transactional may silently not work on that service. If you see this log line, don't ignore it.