[Spring] Bean life cycle source code analysis summary

[Spring] Bean life cycle source code summary

image-20220403143637972

1. Case verification

Define two beans A, B and implement three extension points of MyBeanFactoryProcess, MyBeanProcessor, MyInstantiationAwareBeanPostProcessors

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

 <bean id="a" class="com.sgg.bean.A" init-method="init"/>
 <bean id="b" class="com.sgg.bean.B"/>

 <bean id="myBeanFactoryProcess" class="com.sgg.process.MyBeanFactoryProcess"/>
 <bean id="myBeanProcessor" class="com.sgg.process.MyBeanProcessor"/>
 <bean id="myInstantiationAwareBeanPostProcessors" class="com.sgg.process.MyInstantiationAwareBeanPostProcessors"/>



</beans>

A

image-20220403144206176

B

image-20220403144218921

MyBeanFactoryProcess

image-20220403144253316

`MyBeanProcessor

image-20220403144308958

MyInstantiationAwareBeanPostProcessors

image-20220403144325799

output result

image-20220403143801713

2. Summary

2.1 BeanFactoryPostProcessor

After creating the bean factory to parse and generate bd, we can get the bean factory object by implementing BeanFactoryPostProcessor and modify the definition information of the started bean

2.2 InstantiationAwareBeanPostProcessor

Before instantiating the bean, we can implement InstantiationAwareBeanPostProcessor and rewrite the postProcessBeforeInitialization method to add an object to the container and end the instantiation of the current bean

After instantiating the bean, we can implement InstantiationAwareBeanPostProcessor and rewrite the postProcessAfterInstantiation method to return true or false to decide whether to perform property filling

2.3 BeanPostProcessor

Before initializing the bean, we can implement BeanPostProcessor to rewrite the postProcessBeforeInitialization method to change the bean corresponding to the current beanName

After initializing the bean, we can implement BeanPostProcessor to rewrite the postProcessAfterInitialization method to get the bean object after initialization.

Guess you like

Origin blog.csdn.net/JAVAlife2021/article/details/123937456