Spring BeanPostProcessor
A bean post processor allows additional processing before and after the bean initialization callback method. The main characteristic of a bean post processor is that it will process all the bean instances in the IoC container one by one, not just a single bean instance. Typically, bean post processors are used for checking the validity of bean properties or altering bean properties according to certain criteria.
Spring bean post processor using BeanPostProcessor class
To create a bean post processor class in spring, you will need to implement the BeanPostProcessor
interface and implement it’s postProcessBeforeInitialization()
and postProcessAfterInitialization()
methods. Then Spring will pass each bean instance to these two methods before and after calling the initialization callback method where you can process the bean instance the way you like.
Typically spring’s DI container does following things to create a bean, you request for:
- Create the bean instance either by a constructor or by a factory method
- Set the values and bean references to the bean properties
- Call the setter methods defined in the all the aware interfaces
- Pass the bean instance to the postProcessBeforeInitialization() method of each bean post processor
- Call the initialization callback methods
- Pass the bean instance to the postProcessAfterInitialization() method of each bean post processor
- The bean is ready to be used
- When the container is shut down, call the destruction callback methods
To register a bean post processor in your application context file, declare an instance of the processor in the bean configuration file, and then it will get registered automatically.
Bean post processor example
To show the example usage, I am using EmployeeDAOImpl
class as follow:
|
The configuration for this bean and it’s post processor is as follow:
|
Now let’s start the DI container and see the output:
|
Clearly, post processor methods were called before and after initialization method.
post a comment