Spring
May 29, 2020

M01 Q13 What is a BeanFactoryPostProcessor and PropertySourcesPlaceholderConfigurer?

What is a BeanFactoryPostProcessor and what is it used for?

BeanFactoryPostProcessor is an interface that contains single method postProcessBeanFactory, implementing it allows you to create logic that will modify Spring Bean Metadata before any Bean is created. BeanFactoryPostProcessor does not create any beans, however, it can access and alter Metadata that is used later to create Beans.

When is BeanFactoryPostProcessor invoked?

BeanFactoryPostProcessor is invoked after Spring will read or discover Bean Definitions, but before any Spring Bean is created.

Why would you define a static @Bean method?

Because BeanFactoryPostProcessor is also a Spring Bean, but a special kind of Bean that should be invoked before other types of beans get created, Spring needs to have the ability to create it before any other beans. This is why BeanFactoryPostProcessors needs to be registered from a static method level.

Let's look in the code!

Here I have CustomBeanFactoryPostProcessor and it implements BeanFactoryPostProcessor. And method postProcessBeanFactory just print names all of my beans in the package.

And to register this class I am using the application configuration with a static method. And this static method annotated with @Bean. That informs Spring to create a bean before any other bean.

What is a PropertySourcesPlaceholderConfigurer used for?

PropertySourcesPlaceholderConfigurer is an example of BeanFactoryPostProcessor that is already implemented by Spring.

This class is invoked before any object is created. It is used to resolve properties placeholder in Spring Beans on fields annotated with @Value("${property_name}").