Video in progress

Strong Middle 🌱 Spring

What is the difference between BeanFactoryPostProcessor and BeanPostProcessor?

A BeanFactoryPostProcessor works on the bean definitions (BeanDefinition) before any beans are created. A BeanPostProcessor works on the finished bean objects.

📖 Answer

The order in time:

1. Configuration is read → list of BeanDefinitions
2. BeanFactoryPostProcessors       ← change definitions, add new ones
3. Beans are created
4. BeanPostProcessors              ← change finished objects or wrap them in proxies

An example of a BFPP: ConfigurationClassPostProcessor reads @Configuration, @ComponentScan and @Import and registers the bean definitions. It is one of the most important post-processors in Spring. PropertySourcesPlaceholderConfigurer replaces the ${...} placeholders in definitions with values.

BeanDefinitionRegistryPostProcessor is its extension, for adding new bean definitions from code.

There is one rule: if you declare a BFPP with a @Bean method, make the method static:

@Bean
static PropertySourcesPlaceholderConfigurer placeholders() { ... }

Otherwise Spring creates the whole @Configuration class very early for the BFPP, and @Value/@Autowired inside it stop working.

In ordinary business code you almost never write a BFPP. It is mostly for people who write libraries and frameworks.