Nine, BeanPostProcessor

Time:2022-11-25

1. What is BeanPostProcessor?

The so-called BeanPostProcessor is actually a window opened by Spring for us, just like an interceptor, before the bean object is initialized and after the initialization is completed, the bean can be further packaged;

The role of BeanPostProcessor: to reprocess the objects created by the Spring factory, it also achieves the realization of AOP

BeanPostProcessor is essentially an interface. By implementing the method of this interface, the Bean can be packaged
Nine, BeanPostProcessor
Remark: In the above figure, the creation of a bean will first call the no-argument construction of the class, then inject (DI), then enter postProcessBeforeInitialization, then initialize the bean, and then go to postProcessAfterInitiazation after initialization, and finally give it to the caller. Note that the two parameters Object bean in the method are the bean objects created by Spring, and the beanName is the id value we declared in the tag
1.1 Practical Attention
In actual combat, we seldom deal with the initialization of Spring, so there is no need to distinguish the Before method or the After method. We only need to wrap the bean before giving the bean to the caller to achieve our goal, so we only need Just implement an After method
But what we need to pay attention to is that the Before method does not need to do any bean processing, but must return the bean object
2. Practical steps
Step 1: Write your BeanPostProcessor class to inherit the BeanPostProcessor interface and override the method

public class MyBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        //If this method does not do any processing on the bean, it needs to return the bean like a drummer
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof Catagory) {
            ((Catagory) bean).setName("Paul-Paul");
            ((Catagory) bean).setOrder(25);
        }
        return bean;
    }
}

Step 2: Create your bean object (not shown here because it is too simple)
Step 3: Inject the test bean and processor bean in the configuration file

<! --1. Inject the Catagory object -->
<bean id="catagory" class="cn.paul.spring.demo.hellospring.entity.Catagory">
    <property name="name" value="Jack"/>
    <property name="order" value="18"/>
</bean>
<! 2. Declare the BeanPostProcessor-->
<bean id="myPostProess" class="cn.paul.spring.demo.hellospring.process.MyBeanPostProcessor"/>
<! --3. Inject another object for comparison test -->
<bean id="user" class="cn.paul.spring.demo.hellospring.entity.User"/>