Spring5 source code 5-Bean life cycle post processor

Time:2022-11-24

Spring5 source code 5-Bean life cycle post processor

Mainly explain three lifecycle enhancers:

BeanFactoryPostProcessor:BeanFactorypost processor

BeanDefinitionRegistryPostProcessor: bean definition registration post processor
BeanFactoryPostProcessor
BeanPostProcessor: Bean post processor

BeanPostProcessor
MergedBeanDefinitionPostProcessor
SmartInstantiationAwareBeanPostProcessor
InstantiationAwareBeanPostProcessor
InitializingBean

DisposableBean (We will not explain the destruction scheme for the time being)

1.1 What is BeanPostProcessor
BeanPostProcessor is a very important extension interface provided by Spring, and many functions inside Spring are also completed through BeanPostProcessor (the most typical one seen so far is the injection of AnnotationAwareAspectJAutoProxyCreator).

1.2 Types of BeanPostProcessor
There are many subclasses of BeanPostProcessor in Spring (there are 46 idea), such as

InstantiationAwareBeanPostProcessorAdapter: Plays a very important role in Spring’s bean loading process
AnnotationAwareAspectJAutoProxyCreator: works during property injection during bean creation
AspectJAwareAdvisorAutoProxyCreator: The realization of Aspect’s AOP function also depends on the characteristics of BeanPostProcessor.
1.3 Creation timing
BeanFactoryPostProcessor: Intervene in the creation of BeanDefinition when Spring starts.

BeanPostProcessor: One is the creation of the BeanDefinition corresponding to the Bean. The second is the creation of Bean instances. Because in the Spring container, the creation of the Bean is not just through reflection. During the creation process, it is necessary to consider some properties of the Bean in the Spring container, so the BeanDefinition not only contains the Bean Class file information, but also includes Some attributes of the current Bean in the Spring container, such as the scope in the container, whether it is lazy loaded, aliases and other information. When the Bean is instantiated and created, it needs to rely on the corresponding BeanDefinition to provide corresponding information. .

And because BeanPostProcessor is involved in the Bean creation process. So its creation must be before ordinary beans. In fact, the BeanPostProcessor is created when the container is refreshed when Spring starts.

The BeanDefinition creation timing of BeanPostProcessor is no different from that of ordinary beans. They are all completed in BeanFactoryPostProcessor when Spring starts (to be exact, it is completed in ConfigurationClassPostProcessor).

The instance creation of BeanPostProcessor is prior to the creation of ordinary beans, and the AbstractApplicationContext#registerBeanPostProcessors method will be called during the Spring startup process. In this method, Spring will obtain all BeanPostProcessor type beanNames from the container, obtain the corresponding instances through the beanFactory.getBean method, sort them and register them in the BeanFactory.beanPostProcessors property. When the container needs to execute the BeanPostProcessor method, it can be directly obtained from the beanPostProcessors can be obtained from.

2. Case
Define several test classes separately to implement the post-processor of the bean:

BeanDefinitionRegistryPostProcessor:

/**
 * BeanFactory post processor, PriorityOrdered, Ordered
 */
@Component
public class MyBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {
   public MyBeanDefinitionRegistryPostProcessor(){
      System.out.println("MyBeanDefinitionRegistryPostProcessor");
   }

   @Override //Execute immediately
   public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
      System.out.println("MyBeanDefinitionRegistryPostProcessor....postProcessBeanFactory...");
   }

   @Override //First executed
   public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
      System.out.println("MyBeanDefinitionRegistryPostProcessor...postProcessBeanDefinitionRegistry...");
      //Enhance the registration center of bean definition information, such as registering components yourself

   }
}

copy code
BeanFactoryPostProcessor:

/**
 * Post-processor of BeanFactory
 */
@Component
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

   public MyBeanFactoryPostProcessor(){
      System.out.println("MyBeanFactoryPostProcessor...");
   }

   @Override
   public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
      System.out.println("BeanFactoryPostProcessor....postProcessBeanFactory==>"+beanFactory);
   }
}

copy code
BeanPostProcessor:

/**
 * PostProcessor of the Bean component;
 */
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {

   public MyBeanPostProcessor(){
      System.out.println("MyBeanPostProcessor...");
   }

   public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
      System.out.println("MyBeanPostProcessor...postProcessAfterInitialization..."+bean+"==>"+beanName);
      return bean;
   }

   public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
      System.out.println("MyBeanPostProcessor...postProcessBeforeInitialization..."+bean+"==>"+beanName);
      return bean; // new Object();
   }
}

copy code
InstantiationAwareBeanPostProcessor:

@Component
public class MyInstantiationAwareBeanPostProcessor implements InstantiationAwareBeanPostProcessor {

   public MyInstantiationAwareBeanPostProcessor(){
      System.out.println("MyInstantiationAwareBeanPostProcessor...");
   }

   //Post-processing before initialization, Spring leaves us a callback to create an object for this component.
   public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
      System.out.println("MyInstantiationAwareBeanPostProcessor...postProcessBeforeInstantiation=>"+beanClass+"--"+beanName);
      //if(class.isAssFrom(Cat.class)){return new Dog()}
      //If we created the object ourselves return. Spring won't help us create objects, use our own objects? The object we created, Spring will save the single instance? Or every time getBean is transferred to us to create a new one?
      return null;
   }

   // Whether to allow the remaining post-processors to continue processing the bean
   public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
      //Change some properties in the bean that Spring doesn't care about in advance
      System.out.println("MyInstantiationAwareBeanPostProcessor...postProcessAfterInstantiation=>"+bean+"--"+beanName);
      return true; //Return false to complete the bean assignment
   }
   //Parse custom annotations for attribute value injection; pvs encapsulates all attribute information.
   public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName)
         throws BeansException { //@GuiguValue();redis
      System.out.println("MyInstantiationAwareBeanPostProcessor...postProcessProperties=>"+bean+"--"+beanName);
      return null;
   }

// public PropertyValues postProcessPropertyValues(
//       PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {
//    System.out.println("MyInstantiationAwareBeanPostProcessor...postProcessProperties");
//    return pvs;
// }
}

copy code
MergedBeanDefinitionPostProcessor:

@Component
public class MyMergedBeanDefinitionPostProcessor implements MergedBeanDefinitionPostProcessor {

   public MyMergedBeanDefinitionPostProcessor(){
      System.out.println("MyMergedBeanDefinitionPostProcessor...");
   }

   @Override
   public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
      System.out.println("MyMergedBeanDefinitionPostProcessor...postProcessBeforeInitialization...=>"+bean+"--"+beanName);
      return bean; //null
   }

   @Override
   public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
      System.out.println("MyMergedBeanDefinitionPostProcessor...postProcessAfterInitialization..=>"+bean+"--"+beanName);
      return null;
   }

   @Override
   public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
      System.out.println("MyMergedBeanDefinitionPostProcessor...postProcessMergedBeanDefinition..=>"+beanName+"--"+beanType+"---"+beanDefinition);
   }

   @Override
   public void resetBeanDefinition(String beanName) {
      System.out.println("MyMergedBeanDefinitionPostProcessor...resetBeanDefinition.."+beanName);

   }
}

copy code
SmartInstantiationAwareBeanPostProcessor:

@Component //bean is used during proxy enhancement
public class MySmartInstantiationAwareBeanPostProcessor implements SmartInstantiationAwareBeanPostProcessor {

   public MySmartInstantiationAwareBeanPostProcessor(){
      System.out.println("MySmartInstantiationAwareBeanPostProcessor...");
   }

   //Predict the bean type, and change the component type for the last time.
   public Class<?> predictBeanType(Class<?> beanClass, String beanName) throws BeansException {
      System.out.println("MySmartInstantiationAwareBeanPostProcessor...predictBeanType=>"+beanClass+"--"+beanName);
      return null;
   }

    //returns a list of constructor candidates we want to use
   public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, String beanName) throws BeansException {
      System.out.println("MySmartInstantiationAwareBeanPostProcessor...determineCandidateConstructors=>"+beanClass+"--"+beanName);
      //return a constructor we specified
      return null;
   }

     //Return to the early bean reference and define the bean information in the third-level cache
   public Object getEarlyBeanReference(Object bean, String beanName) throws BeansException {
      System.out.println("MySmartInstantiationAwareBeanPostProcessor...getEarlyBeanReference=>"+bean+"--"+beanName);

      return bean; //
   }

}

copy code
InitializingBean:

@Component
public class CatInitializingBean implements InitializingBean {

   public CatInitializingBean(){
      System.out.println("cat is created...");
   }

   private String name;


   @Value("${JAVA_HOME}") //automatic assignment function
   public void setName(String name) {
      System.out.println("cat....setName is being assigned and called....");
      this.name = name;
   }
   // How does the annotation define that this is an initialization method?
   public String getName() {
      return name;
   }

   @Override
   public void afterPropertiesSet() throws Exception {
      System.out.println("CatInitializingBean..afterPropertiesSet...");
   }

   @Autowired
   private void init() {
      System.out.println("CatInitializingBean init....");
   }

}

copy code
Debugging: Put a breakpoint on each constructor and method, mainly to see when is the execution time of each method?

3. Source code analysis
The entry is still: org.springframework.context.support.AbstractApplicationContext#refresh:

// The twelve steps of container refresh
@Override
public void refresh() throws BeansException, IllegalStateException {
   synchronized (this.startupShutdownMonitor) {
      // The status of the container startup
      StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");

      // Prepare this context for refreshing.
      // 1. Prepare the context
      prepareRefresh();

      // Tell the subclass to refresh the internal bean factory.
      /** 1. Create a BeanFactory object
      * 2. XML parsing
      * Traditional tag analysis: bean, import, etc.
      * Custom tag parsing such as:<context:component-scan base-package="org.example"/>
      * Custom tag parsing process:
      * a. Find the corresponding namespaceUri according to the header information of the currently parsed tag
      * b. Load spring so the spring.handlers file in the jar. and establish a mapping relationship
      * c. According to the namespaceUri, find the corresponding class that implements the NamespaceHandler interface from the mapping relationship
      * d. Call the init method of the class. The init method is a parsing class registered with various custom tags
      * e. Find the corresponding parsing class according to the namespaceUri, and then call the paser method to complete the tag parsing
      * 3. Encapsulate the parsed xml tags into BeanDefinition objects
      */
      // 2. Factory creation: When BeanFactory is first created, there is xml parsing logic
      ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

      // Prepare the bean factory for use in this context.
      // 3. Pre-prepare the factory and register the environment information in the container as a single-instance bean to facilitate subsequent automatic assembly
      // And put some post-processors (monitoring, xxxAware function)
      prepareBeanFactory(beanFactory);

      try {
         //  Allows post-processing of the bean factory in context subclasses.
         // Template method reserved for subclasses, allowing subclasses to continue to perform some processing on the factory
         postProcessBeanFactory(beanFactory);

         StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
         // Invoke factory processors registered as beans in the context.
         // 5. [Big core] Factory enhancement: Execute all BeanFactory post-enhancers Use BeanFactory post-enhancers to modify or enhance the factory
         // The configuration class will also be parsed here
         // BeanDefinitionRegistryPostProcessor BeanFactoryPostProcessor completes calls to these two interfaces
         invokeBeanFactoryPostProcessors(beanFactory);

         // Register bean processors that intercept bean creation.
         // 6. [Core] Register all Bean post-processors
         registerBeanPostProcessors(beanFactory);
         beanPostProcess.end();

         // Initialize message source for this context.
         // 7. Initialize the internationalization component
         initMessageSource();

         // Initialize event multicaster for this context.
         // 8. Initialize the event dispatch function
         initApplicationEventMulticaster();

         // Initialize other special beans in specific context subclasses.
         // 9. Leave it to subclasses to continue to enhance the processing logic
         // This method focuses on understanding the template design pattern, because in springboot, this method is used to start the embedded tomcat
         onRefresh();

         // Check for listener beans and register them.
         // 10. Register event listeners and get all ApplicationListeners from the container
         registerListeners();

         // Instantiate all remaining (non-lazy-init) singletons.
         // 11. [Big core] bean creation: complete BeanFactory initialization (all components in the factory are ready)
         /*
          * This method must be understood to be specific
          * 1. Bean instantiation process
          * 2、ioc
          * 3. Annotation support
          * 4. Execution of BeanPostProcessor
          * 5. The entrance of Aop
          */
         finishBeanFactoryInitialization(beanFactory);

         // Last step: publish corresponding event.
         // 12. Publish event
         finishRefresh();
      }

      catch (BeansException ex) {
         if (logger.isWarnEnabled()) {
            logger.warn("Exception encountered during context initialization - " +
                  "cancelling refresh attempt: " + ex);
         }

         // Destroy already created singletons to avoid dangling resources.
         destroyBeans();

         // Reset 'active' flag.
         cancelRefresh(ex);

         // Propagate exception to caller.
         throw ex;
      }

      finally {
         // Reset common introspection caches in Spring's core, since we
         // might not ever need metadata for singleton beans anymore...
         resetCommonCaches();
         contextRefresh.end();
      }
   }
}

copy code
We mainly analyze several methods:

3.1 invokeBeanFactoryPostProcessors(beanFactory)
BeanDefinitionRegistryPostProcessorand BeanFactoryPostProcessorMethod processing is all in this step.

Directly see PostProcessorRegistrationDelegate# invokeBeanFactoryPostProcessors () :

public static void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
// WARNING: Although it may appear that the body of this method can be easily
// refactored to avoid the use of multiple loops and multiple lists, the use
// of multiple lists and multiple passes over the names of processors is
// intentional. We must ensure that we honor the contracts for PriorityOrdered
// and Ordered processors. Specifically, we must NOT cause processors to be
// instantiated (via getBean() invocations) or registered in the ApplicationContext
// in the wrong order.
//
// Before submitting a pull request (PR) to change this method, please review the
// list of all declined PRs involving changes to PostProcessorRegistrationDelegate
// to ensure that your proposal does not result in a breaking change:
// https://github.com/spring-projects/spring-framework/issues?q=PostProcessorRegistrationDelegate+is%3Aclosed+label%3A%22status%3A+declined%22
// Invoke BeanDefinitionRegistryPostProcessors first, if any.
Set<String> processedBeans = new HashSet<>();
// First get the default BeanFactoryPostProcessor at the bottom layer, the container will inject ConfigurationClassPostProcessor, and post-processing the configuration class
if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
BeanDefinitionRegistryPostProcessor registryProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
registryProcessor.postProcessBeanDefinitionRegistry(registry);
registryProcessors.add(registryProcessor);
}
else {
regularPostProcessors.add(postProcessor);
}
}
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!
// Separate between BeanDefinitionRegistryPostProcessors that implement
// PriorityOrdered, Ordered, and the rest.
List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
// First, get all BeanDefinitionRegistryPostProcessor from the factory
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
// Get all BeanDefinitionRegistryPostProcessors that implement the PriorityOrdered interface
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
// Get this component from the factory (creation of the getBean component) and put it in this collection
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
// sort by priority
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
// todo executes these BeanDefinitionRegistryPostProcessor
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
currentRegistryProcessors.clear();
// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
// Next, get all BeanDefinitionRegistryPostProcessors that implement the Ordered interface
for (String ppName : postProcessorNames) {
// Even if the Ordered and PriorityOrdered interfaces are implemented, the PriorityOrdered interface shall prevail
if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
// sort
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
currentRegistryProcessors.clear();
// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
// Finally, we customize and do not implement the priority interface
boolean reiterate = true;
while (reiterate) {
reiterate = false;
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (!processedBeans.contains(ppName)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
reiterate = true;
}
}
// sort,根据类名大小写进行排序
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
// todo implements the BeanDefinitionRegistryPostProcessor.postProcessBeanDefinitionRegistry method
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
// prevent duplicates
currentRegistryProcessors.clear();
}
// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
// todo Next, implement the BeanDefinitionRegistryPostProcessor.postProcessBeanFactory method
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
}
else {
// Invoke factory processors registered with the context instance.
invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
}
// todo above is to execute BeanDefinitionRegistryPostProcessor, below is to execute BeanFactoryPostProcessor
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
List<String> orderedPostProcessorNames = new ArrayList<>();
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {
if (processedBeans.contains(ppName)) {
// skip - already processed in first phase above
}
else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
else {
nonOrderedPostProcessorNames.add(ppName);
}
}
// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
// First, implement the BeanFactoryPostProcessors that implement the PriorityOrdered interface
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
// Next, implement the BeanFactoryPostProcessors that implement the Ordered interface
List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
for (String postProcessorName : orderedPostProcessorNames) {
orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
sortPostProcessors(orderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
// Finally, invoke all other BeanFactoryPostProcessors.
// Finally, execute BeanFactoryPostProcessors that do not implement the priority and sorting interfaces
List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
for (String postProcessorName : nonOrderedPostProcessorNames) {
nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
// todo executes the BeanFactoryPostProcessor.postProcessBeanFactory() method
invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
// Clear cached merged bean definitions since the post-processors might have
// modified the original metadata, e.g. replacing placeholders in values...
beanFactory.clearMetadataCache();
}

copy code
get allBeanDefinitionRegistryPostProcessorand to create the object, first, executePriorityOrderedinterface, and secondly, the implementationOrderedInterface, finally, the implementation does not implement the priority interface, will execute the invokeBeanDefinitionRegistryPostProcessors () method andinvokeBeanFactoryPostProcessors()method.

3.1.1 invokeBeanDefinitionRegistryPostProcessors()

private static void invokeBeanDefinitionRegistryPostProcessors(
Collection<? extends BeanDefinitionRegistryPostProcessor> postProcessors, BeanDefinitionRegistry registry, ApplicationStartup applicationStartup) {
for (BeanDefinitionRegistryPostProcessor postProcessor : postProcessors) {
StartupStep postProcessBeanDefRegistry = applicationStartup.start("spring.context.beandef-registry.post-process")
.tag("postProcessor", postProcessor::toString);
// todo core, the post-processor of the configuration class parses the configuration class here
postProcessor.postProcessBeanDefinitionRegistry(registry);
postProcessBeanDefRegistry.end();
}
}

copy code
The BeanDefinitionRegistryPostProcessor.postProcessBeanDefinitionRegistry method will be executed here.

3.1.2 invokeBeanFactoryPostProcessors()

invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
private static void invokeBeanFactoryPostProcessors(
Collection<? extends BeanFactoryPostProcessor> postProcessors, ConfigurableListableBeanFactory beanFactory) {
for (BeanFactoryPostProcessor postProcessor : postProcessors) {
StartupStep postProcessBeanFactory = beanFactory.getApplicationStartup().start("spring.context.bean-factory.post-process")
.tag("postProcessor", postProcessor::toString);
// todo
postProcessor.postProcessBeanFactory(beanFactory);
postProcessBeanFactory.end();
}
}

copy code
Here, the input parameters are all BeanDefinitionRegistryPostProcessor types, so the BeanDefinitionRegistryPostProcessor.postProcessBeanFactory method will be executed.

3.1.3
Next, get allBeanFactoryPostProcessorand to create the object, first, executePriorityOrderedinterface, and secondly, the implementationOrderedInterface, finally, the execution does not implement the priority interface, it will be executedinvokeBeanFactoryPostProcessors()method.

The input parameter this time is the BeanFactoryPostProcessor object, so the BeanFactoryPostProcessor.postProcessBeanFactory() method will be executed.

3.1.4 beanFactory.getBeanNamesForType()
How to get all components according to type in spring?
DefaultListableBeanFactory#getBeanNamesForType():

@Override
public String[] getBeanNamesForType(@Nullable Class<?> type, boolean includeNonSingletons, boolean allowEagerInit) {
if (!isConfigurationFrozen() || type == null || !allowEagerInit) {
// todo
return doGetBeanNamesForType(ResolvableType.forRawClass(type), includeNonSingletons, allowEagerInit);
}
...
}

copy code

// Get the name of a component in the container
private String[] doGetBeanNamesForType(ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit) {
List<String> result = new ArrayList<>();
// Check all bean definitions.
//Because Spring does not have the corresponding information of class-bean, it can only traverse all beanNames to take out the definition information of all their beanNames, and then check whether they are of the specified type
// Only when the bean instance has not been created here, the post-processor can be used to intervene in the bean type
for (String beanName : this.beanDefinitionNames) {
// Only consider bean as eligible if the bean name is not defined as alias for some other bean.
if (!isAlias(beanName)) {
try {
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
// Only check bean definition if it is complete.
if (!mbd.isAbstract() && (allowEagerInit ||
(mbd.hasBeanClass() || !mbd.isLazyInit() || isAllowEagerClassLoading()) &&
!requiresEagerInitForType(mbd.getFactoryBeanName()))) {
boolean isFactoryBean = isFactoryBean(beanName, mbd);
BeanDefinitionHolder dbd = mbd.getDecoratedDefinition();
boolean matchFound = false;
// Whether containsSingleton(beanName) has created a singleton object
boolean allowFactoryBeanInit = (allowEagerInit || containsSingleton(beanName));
boolean isNonLazyDecorated = (dbd != null && !mbd.isLazyInit());
if (!isFactoryBean) {
if (includeNonSingletons || isSingleton(beanName, mbd, dbd)) {
// Whether the type matches
matchFound = isTypeMatch(beanName, type, allowFactoryBeanInit);
}
}
else {
if (includeNonSingletons || isNonLazyDecorated ||
(allowFactoryBeanInit && isSingleton(beanName, mbd, dbd))) {
// Whether the type matches
matchFound = isTypeMatch(beanName, type, allowFactoryBeanInit);
}
if (!matchFound) {
// In case of FactoryBean, try to match FactoryBean instance itself next.
beanName = FACTORY_BEAN_PREFIX + beanName;
if (includeNonSingletons || isSingleton(beanName, mbd, dbd)) {
matchFound = isTypeMatch(beanName, type, allowFactoryBeanInit);
}
}
}
if (matchFound) {
result.add(beanName);
}
}
}
catch (CannotLoadBeanClassException | BeanDefinitionStoreException ex) {
if (allowEagerInit) {
throw ex;
}
// Probably a placeholder: let's ignore it for type matching purposes.
LogMessage message = (ex instanceof CannotLoadBeanClassException ?
LogMessage.format("Ignoring bean class loading failure for bean '%s'", beanName) :
LogMessage.format("Ignoring unresolvable metadata in bean definition '%s'", beanName));
logger.trace(message, ex);
// Register exception, in case the bean was accidentally unresolvable.
onSuppressedException(ex);
}
catch (NoSuchBeanDefinitionException ex) {
// Bean definition got removed while we were iterating -> ignore.
}
}
}
// Check manually registered singletons too.
for (String beanName : this.manualSingletonNames) {
try {
// In case of FactoryBean, match object created by FactoryBean.
if (isFactoryBean(beanName)) {
if ((includeNonSingletons || isSingleton(beanName)) && isTypeMatch(beanName, type)) {
result.add(beanName);
// Match found for this bean: do not match FactoryBean itself anymore.
continue;
}
// In case of FactoryBean, try to match FactoryBean itself next.
beanName = FACTORY_BEAN_PREFIX + beanName;
}
// Match raw bean instance (might be raw FactoryBean).
if (isTypeMatch(beanName, type)) {
result.add(beanName);
}
}
catch (NoSuchBeanDefinitionException ex) {
// Shouldn't happen - probably a result of circular reference resolution...
logger.trace(LogMessage.format(
"Failed to check manually registered singleton with name '%s'", beanName), ex);
}
}
return StringUtils.toStringArray(result);
}

copy code
The main steps:

Get the names of all components, beanDefinitionNames
Iterate through each component name
Go to the BeanDefinitionMap to find the definition information of the bean
Obtain the type of the component from the definition information
See if this type matches
3.2 registerBeanPostProcessors(beanFactory)
Register all bean post-processors, PostProcessorRegistrationDelegate#registerBeanPostProcessors():

public static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
// WARNING: Although it may appear that the body of this method can be easily
// refactored to avoid the use of multiple loops and multiple lists, the use
// of multiple lists and multiple passes over the names of processors is
// intentional. We must ensure that we honor the contracts for PriorityOrdered
// and Ordered processors. Specifically, we must NOT cause processors to be
// instantiated (via getBean() invocations) or registered in the ApplicationContext
// in the wrong order.
//
// Before submitting a pull request (PR) to change this method, please review the
// list of all declined PRs involving changes to PostProcessorRegistrationDelegate
// to ensure that your proposal does not result in a breaking change:
// https://github.com/spring-projects/spring-framework/issues?q=PostProcessorRegistrationDelegate+is%3Aclosed+label%3A%22status%3A+declined%22
// Obtain all BeanPostProcessors in the container, Bean post-processors
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
// Register BeanPostProcessorChecker that logs an info message when
// a bean is created during BeanPostProcessor instantiation, i.e. when
// a bean is not eligible for getting processed by all BeanPostProcessors.
int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
// Separate between BeanPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
List<String> orderedPostProcessorNames = new ArrayList<>();
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {
// Get all the implementations of the PriorityOrdered interface
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
priorityOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
else {
nonOrderedPostProcessorNames.add(ppName);
}
}
// First, register the BeanPostProcessors that implement PriorityOrdered.
// First, register the BeanPostProcessor that implements the PriorityOrdered interface
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
// Next, register the BeanPostProcessors that implement Ordered.
// Next, register the BeanPostProcessor that implements the Ordered interface
List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
for (String ppName : orderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
orderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
sortPostProcessors(orderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, orderedPostProcessors);
// Now, register all regular BeanPostProcessors.
// Finally, a normal BeanPostProcessor is registered
List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
for (String ppName : nonOrderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
nonOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
// Finally, re-register all internal BeanPostProcessors.
// Finally, register all internal BeanPostProcessors
sortPostProcessors(internalPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, internalPostProcessors);
// Re-register post-processor for detecting inner beans as ApplicationListeners,
// moving it to the end of the processor chain (for picking up proxies etc).
// Re-register the post-processor ApplicationListenerDetector
// put it in the last position of the postprocessor
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}

copy code
In this step, the bean post-processor BeanPostProcessor, MergedBeanDefinitionPostProcessor, SmartInstantiationAwareBeanPostProcessor, InstantiationAwareBeanPostProcessor are all registered and initialized.

3.3 registerListeners()
The core of this is to register the listener event, which we will talk about later, today mainly explains the type of SmartInstantiationAwareBeanPostProcessor.predictBeanType() intervention bean.

/**
* Add beans that implement ApplicationListener as listeners.
* Doesn't affect other listeners, which can be added without being beans.
* Multicasters and listeners are observer patterns, which contain all listeners
*/
protected void registerListeners() {
...
// Get the name of the bean registered by the ApplicationListener in the ioc container
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
for (String listenerBeanName : listenerBeanNames) {
// Get all listeners and save their names in
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
}
...
}

copy code
The getBeanNamesForType() method will also be executed. We have briefly analyzed it before, and we come directly to: AbstractAutowireCapableBeanFactory#predictBeanType method:

@Override
@Nullable
protected Class<?> predictBeanType(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) {
Class<?> targetType = determineTargetType(beanName, mbd, typesToMatch);
// Apply SmartInstantiationAwareBeanPostProcessors to predict the
// eventual type after a before-instantiation shortcut.
if (targetType != null && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
boolean matchingOnlyFactoryBean = typesToMatch.length == 1 && typesToMatch[0] == FactoryBean.class;
// todo executes the SmartInstantiationAwareBeanPostProcessor.predictBeanType method
for (SmartInstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().smartInstantiationAware) {
Class<?> predicted = bp.predictBeanType(targetType, beanName);
if (predicted != null &&
(!matchingOnlyFactoryBean || FactoryBean.class.isAssignableFrom(predicted))) {
return predicted;
}
}
}
return targetType;
}

copy code
When executing the post processor of the Bean factory in Section 3.1, hasInstantiationAwareBeanPostProcessors() is false, so this method cannot be entered. The reason is that when the invokeBeanFactoryPostProcessors() method is used, the BeanPostProcessor does not exist in the container yet, so it will not be executed.

However, registerListeners() is after the registerBeanPostProcessors() method, so this method can be executed, that is, SmartInstantiationAwareBeanPostProcessor.predictBeanType() interferes with the bean’s component type.

3.4 finishBeanFactoryInitialization()
Complete BeanFactory initialization (all components in the factory are fine).beanFactory.preInstantiateSingletons()-> getBean`(beanName)->doGetBean->createBean`

protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
...
try {
// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
// todo gives us a chance in advance to return the proxy object of the component
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
return bean;
}
}
...
try {
// todo creates object
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isTraceEnabled()) {
logger.trace("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
...
}

copy code

3.4.1 resolveBeforeInstantiation(beanName, mbdToUse)
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
Object bean = null;
if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
// Make sure bean class is actually resolved at this point.
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
Class<?> targetType = determineTargetType(beanName, mbd);
if (targetType != null) {
// todo InstantiationAwareBeanPostProcessor. PostProcessBeforeInstantiation () method
bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
if (bean != null) {
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
}
}
}
mbd.beforeInstantiationResolved = (bean != null);
}
return bean;
}

copy code

protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {
for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
// todo execution
Object result = bp.postProcessBeforeInstantiation(beanClass, beanName);
if (result != null) {
return result;
}
}
return null;
}

copy code
Implement the InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation() method here. If the method returns true, execute the applyBeanPostProcessorsAfterInitialization() method directly:

public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
// todo executes all BeanPostProcessor.postProcessAfterInitialization() methods
// All BeanPostProcessor types
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessAfterInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}

copy code
All BeanPostProcessor.postProcessAfterInitialization() methods are implemented here.

Next, let’s look at the doCreateBean method.

3.4.2 doCreaeBean

protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
// Instantiate the bean.
BeanWrapper instanceWrapper = null;
// is it a singleton
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
// todo creates a Bean instance, the object created by the no-argument constructor is used by default, and the component instance is created
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
Object bean = instanceWrapper.getWrappedInstance();
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}
// Allow post-processors to modify the merged bean definition.
// MergedBeanDefinitionPostProcessor post processor to modify the BeanDefinition information
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
// todo executes MergedBeanDefinitionPostProcessor.postProcessMergedBeanDefinition() method
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Post-processing of merged bean definition failed", ex);
}
mbd.postProcessed = true;
}
}
// Eagerly cache singletons to be able to resolve circular references
// even when triggered by lifecycle interfaces like BeanFactoryAware.
// Expose the single instance bean in advance to solve the problem of circular references
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
if (logger.isTraceEnabled()) {
logger.trace("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
// Add to
// Beans in the third-level cache will also be enhanced by post-processing
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
// Initialize the bean instance.
Object exposedObject = bean;
try {
// each property assignment in the todo object
populateBean(beanName, mbd, instanceWrapper);
// todo initializes the bean
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
...
return exposedObject;
}

copy code

3.4.2.1 createBeanInstance(beanName, mbd, args)

Create a bean instance, using the no-argument constructor by default.

protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
// Make sure bean class is actually resolved at this point.
// create bean type
Class<?> beanClass = resolveBeanClass(mbd, beanName);
...
// Candidate constructors for autowiring?
// todo candidate constructor SmartInstantiationAwareBeanPostProcessor.determineCandidateConstructors()
// Post-processors have the opportunity to decide which constructor to use for the current bean here
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
// Constructor way automatic injection and object creation
return autowireConstructor(beanName, mbd, ctors, args);
}
// Preferred constructors for default construction?
// Use the default high-priority constructor set by yourself
ctors = mbd.getPreferredConstructors();
if (ctors != null) {
return autowireConstructor(beanName, mbd, ctors, null);
}
// No special handling: simply use no-arg constructor.
// Create an object for the current component using the no-argument constructor by default
return instantiateBean(beanName, mbd);
}

copy code
The constructor can be decided in the determineConstructorsFromBeanPostProcessors method.

protected Constructor<?>[] determineConstructorsFromBeanPostProcessors(@Nullable Class<?> beanClass, String beanName)
throws BeansException {
if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) {
for (SmartInstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().smartInstantiationAware) {
// todo implements the SmartInstantiationAwareBeanPostProcessor.determineCandidateConstructors() method
Constructor<?>[] ctors = bp.determineCandidateConstructors(beanClass, beanName);
if (ctors != null) {
return ctors;
}
}
}
return null;
}

copy code
Execute the SmartInstantiationAwareBeanPostProcessor.determineCandidateConstructors() method here.

3.4.2.2 applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName)

protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
// todo executes MergedBeanDefinitionPostProcessor.postProcessMergedBeanDefinition() method
for (MergedBeanDefinitionPostProcessor processor : getBeanPostProcessorCache().mergedDefinition) {
processor.postProcessMergedBeanDefinition(mbd, beanType, beanName);
}
}

copy code
Execute the MergedBeanDefinitionPostProcessor.postProcessMergedBeanDefinition() method here.

3.4.2.3 populateBean(beanName, mbd, instanceWrapper)

Assign values ​​to each attribute.

protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
...
// Before attribute assignment, the postprocessor can prepare something in advance
// @AutoWired assignment is also here AutowiredAnnotationBeanPostProcessor (return true directly without other processing), which can interrupt the initialization behavior
//
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
// todo implements the InstantiationAwareBeanPostProcessor.postProcessAfterInstantiation() method
if (!bp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
return;
}
}
} // The above post-processors can interrupt the initialization behavior below
...
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
PropertyDescriptor[] filteredPds = null;
if (hasInstAwareBpps) {
if (pvs == null) {
// specified by the property tag in xml
pvs = mbd.getPropertyValues();
}
// Annotated version of the attribute assignment post-processor processing attributes (true automatic assembly)
for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
// todo executes the InstantiationAwareBeanPostProcessor.postProcessProperties() method
PropertyValues pvsToUse = bp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
pvsToUse = bp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
return;
}
}
pvs = pvsToUse; // Encapsulates all the property names and values ​​of the current bean, which can be processed by the post-processor
}
}
...
if (pvs != null) { // Set the previously processed PropertyValues ​​in the bean, mainly because the above steps did not set the properties in the bean
// All configurations of the xml version will come here to assign values ​​to attributes
applyPropertyValues(beanName, mbd, bw, pvs);
}
}

copy code
Here, two post-processor methods are executed:

Execute the InstantiationAwareBeanPostProcessor.postProcessAfterInstantiation() method
Execute the InstantiationAwareBeanPostProcessor.postProcessProperties() method
3.4.2.4 initializeBean(beanName, exposedObject, mbd)
Initialize the bean.
protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareMethods(beanName, bean);
return null;
}, getAccessControlContext());
}
else {
// The component has an Aware interface, Aware first; BeanNameAware BeanClassLoaderAware BeanFactoryAware
invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
// todo executes the BeforeInitialization of the post-processor, which can change the previously created bean instance
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
// todo executes the initialization method to implement the interface of InitializingBean
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
throw new BeanCreationException(
(mbd != null ? mbd.getResourceDescription() : null),
beanName, "Invocation of init method failed", ex);
}
if (mbd == null || !mbd.isSynthetic()) {
// todo executes the postProcessAfterInitialization of the post processor
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}

copy code
Here, three post-processor methods are implemented:

Execute all BeanPostProcessor.postProcessBeforeInitialization() methods
Implement the interface of InitializingBean, execute the initialization method and implement the InitializingBean.afterPropertiesSet() method

Execute all BeanPostProcessor.postProcessAfterInitialization() methods
At this point, the execution timing of all post-processor methods in the bean life cycle has been displayed