Your praise is my biggest motivation, and I look forward to making progress together with you

This article mainly deals with: Spring Bean post-processing into the container process.

6.registerBeanPostProcessors

protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
    PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}
Copy the code

The BeanPostProcessor processing in Spring is divided into two processes. The implementation of the built-in BeanPostProcessor subclass is added to the IoC container. This is done through the prepareBeanFactory() procedure in the Refresh () method. Such as ApplicationContextAwareProcessor ApplicationListenerDetector. Is in for a ImportAwareBeanPostProcessor, when handling ConfigurationClassPostProcessor @ Configuration annotation class generation when additional agent to join in a container. Finally, in the Spring for a BeanPostProcessor implementation class, is the refresh () method of one step registerBeanPostProcessors () to complete the registration, Such as BeanPostProcessorChecker, CommonAnnotationBeanPostProcessor and AutowiredAnnotationBeanPostProcessor, CommonAnnotationBeanPostProcessor. Thus, at the point of container initialization, the container contains the implementation of the backend processor for six beans without implementing the BeanPsotProcessor itself. One for registerBeanPostProcessors detailed code () method, the following analysis one by one:

public static void registerBeanPostProcessors(
        ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {

    // Get all BeanDefinitionMap BeanPostProcessors
    String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true.false);
  / * ** BeanPostProcessorChecker is a normal message print that may have some cases* When the backend processor in Spring's configuration has started the bean initialization before it has been registered* prints out the value set in BeanPostProcessorChecker* /  int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;  // new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount)  / / create a default PostProcessorRegistrationDelegate BeanPostProcessorChecker PostProcessorRegistrationDelegate  // a static inner class that implements the BeanPostProcessor interface  beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));   / * ** Use priorityOrdered to ensure order* /  List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();  List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();  / * ** Use ordered to ensure order* /  List<String> orderedPostProcessorNames = new ArrayList<>();  / * ** disorderly BeanPostProcessor* /  List<String> nonOrderedPostProcessorNames = new ArrayList<>();  for (String ppName : postProcessorNames) {  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 step, register all BeanPostProcessors that implement PriorityOrdered* /  sortPostProcessors(priorityOrderedPostProcessors, beanFactory);  registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);   / * ** Second, register all Ordered BeanPostProcessors* /  List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>();  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);   / * ** Step 3, register unordered BeanPostProcessors* /  List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>();  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.  / * ** registered all BeanPostProcessors MergedBeanDefinitionPostProcessor type* /  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).  beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext)); } Copy the code

Add the Bean’s post-processor to the container

public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
    Assert.notNull(beanPostProcessor, "BeanPostProcessor must not be null");
    // Remove from old position, if any
    this.beanPostProcessors.remove(beanPostProcessor);
    // Track whether it is instantiation/destruction aware
 if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {  this.hasInstantiationAwareBeanPostProcessors = true;  }  if (beanPostProcessor instanceof DestructionAwareBeanPostProcessor) {  this.hasDestructionAwareBeanPostProcessors = true;  }  // Add to end of list  this.beanPostProcessors.add(beanPostProcessor); } Copy the code

At this point, the parsing of the container initialization parts in Spring is done. By now, the contents of the container are basically complete, as shown in the following container diagram:

7.initMessageSource()

protected void initMessageSource(a) {
    ConfigurableListableBeanFactory beanFactory = getBeanFactory();
    if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
        this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
        // Make MessageSource aware of parent MessageSource.
 if (this.parent ! =null && this.messageSource instanceof HierarchicalMessageSource) {  HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;  if (hms.getParentMessageSource() == null) {  // Only set parent context as parent MessageSource if no parent MessageSource  // registered already.  hms.setParentMessageSource(getInternalParentMessageSource());  }  }  if (logger.isTraceEnabled()) {  logger.trace("Using MessageSource [" + this.messageSource + "]");  }  }  else {  // Use empty MessageSource to be able to accept getMessage calls.  DelegatingMessageSource dms = new DelegatingMessageSource();  dms.setParentMessageSource(getInternalParentMessageSource());  this.messageSource = dms;  beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);  if (logger.isTraceEnabled()) {  logger.trace("No '" + MESSAGE_SOURCE_BEAN_NAME + "' bean, using [" + this.messageSource + "]");  }  } } Copy the code

Determine if there is a name for the messageSource bean in the beanFactory, if any, from the beanFactory and figure out whether obtained HierarchicalMessageSource type, if is to set the parent sources If not, Create a New DelegatingMessageSource class as the Bean for the messageSource.

8.initApplicationEventMulticaster()

protected void initApplicationEventMulticaster(a) {
    ConfigurableListableBeanFactory beanFactory = getBeanFactory();
    if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
        this.applicationEventMulticaster =
                beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
 if (logger.isTraceEnabled()) {  logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");  }  }  else {  this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);  beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);  if (logger.isTraceEnabled()) {  logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " +  "[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");  }  } } Copy the code

Initialization ApplicationEventMulticaster if the user-defined event broadcast, then use the user custom event broadcast device if the user does not have a custom event broadcast, Then use the default ApplicationEventMulticaster SimpleApplicationEventMulticaster namely.

9.onRefresh()

protected void onRefresh(a) throws BeansException {
    // For subclasses: do nothing by default.
}
Copy the code

Empty methods, which Spring reserves for subclasses to implement if needed.

10.registerListeners();

protected void registerListeners(a) {
    // Register statically specified listeners first.
    // Hardcoded way to register listener handling
    for(ApplicationListener<? > listener : getApplicationListeners()) {        getApplicationEventMulticaster().addApplicationListener(listener);
 }   // Do not initialize FactoryBeans here: We need to leave all regular beans  // uninitialized to let post-processors apply to them!  // Config file registration listener handling  String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true.false);  for (String listenerBeanName : listenerBeanNames) {  getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);  }   // Publish early application events now that we finally have a multicaster...  Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;  this.earlyApplicationEvents = null;  if(earlyEventsToProcess ! =null) {  for (ApplicationEvent earlyEvent : earlyEventsToProcess) {  getApplicationEventMulticaster().multicastEvent(earlyEvent);  }  } } Copy the code

Retrieve the listener in the container, and then to get the applicationEventMulticaster current container, call addApplicationListener add. ApplicationEventMulticaster is just initialized, here is SimpleApplicationEventMulticaster if is empty.

Get a Bean of type ApplicationListener from the BeanFactory and add it as ListenerBeans.

Get the events that need to be published in advance and broadcast them.

The last

At this point, the refresh () method of each method of study, with only a finishBeanFactoryInitialization (). There are a number of new processes involved in this approach that are closely related to Bean instantiation. A later article will cover Bean instantiation. This is where the instantiation entry for the Bean comes in.

This article is formatted using MDNICE