Header Ads

ad

BeanPostProcessor

Assigning some values to spring bean properties after injection is done, is called post processing. BeanPostProcessor is used to perform this post processing...

BeanPostProcessor methods execute for each bean class object that is created by IOC container...

BeanPostProcessor methods are common for all bean that are configured in configuration file..

NOTE :- Even though bean class is configured in xml file and if IOC container has not created object for that bean class then no BeanPostProcessor will execute for that bean class...

How to create BeanPostProcessor ?

To develop BeanPostProcessor we need to take a class that implements BeanPostProcessor interface and should provide implementation for following two methods:

a) postProcessBeforeInitialization(Object bean, String beanId)
b) postProcessAfterInitialization(Object bean, String beanId)

Upto Spring 4.x BeanPostProcessor interface was given as a normal interface without default methods. But from Spring 5.x, the same BeanPostProcessor is given with default methods. Here, we need not to implement both the above methods. Since methods are default we can implement any of the methods as per requirement...


Example:
  1. public class MyBPP implements BeanPostProcessor{  
  2.     public Object postProcessBeforeInitialization(Object bean, String beanName){
  3.       --------
  4.       // executes first
  5.       // executes before afterPropertiesSet() method of bean class
  6.       --------
  7.     } 
  8.    public Object postProcessAfterInitialization(Object bean, String beanName){
  9.     ------------
  10.      //executes second
  11.      //executes after custom init() method of every bean class
  12.     -----------
  13.    }
  14. }  


Real Time use of BeanPostProcessor

In real time BeanPostProcessor is used to place common post processing initialization logic that is required for multiple beans like assigning system date as date of joining or last modification date or updation date and etc...

This concept is very useful towards auditing, loggings activities...





No comments