Spring Boot Records (12)

1. Wait until spring's refresh method to registerBeanPostProcessors

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

The same process as the previous BeanProcessorFactory registration

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

   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<BeanPostProcessor>();
   List<BeanPostProcessor> internalPostProcessors = new ArrayList<BeanPostProcessor>();
   List<String> orderedPostProcessorNames = new ArrayList<String>();
   List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
   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, register the BeanPostProcessors that implement PriorityOrdered.
   sortPostProcessors(beanFactory, priorityOrderedPostProcessors);
   registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

   // Next, register the BeanPostProcessors that implement Ordered.
   List<BeanPostProcessor> orderedPostProcessors = new ArrayList<BeanPostProcessor>();
   for (String ppName : orderedPostProcessorNames) {
      BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
      orderedPostProcessors.add(pp);
      if (pp instanceof MergedBeanDefinitionPostProcessor) {
         internalPostProcessors.add(pp);
      }
   }
   sortPostProcessors(beanFactory, orderedPostProcessors);
   registerBeanPostProcessors(beanFactory, orderedPostProcessors);

   // Now, register all regular BeanPostProcessors.
   List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanPostProcessor>();
   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.
   sortPostProcessors(beanFactory, internalPostProcessors);
   registerBeanPostProcessors(beanFactory, internalPostProcessors);

   beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}

2. Wait until the BeanProcessor is initialized and execute initMessageSource

protected void initMessageSource() {
    //What we get here is DefaultListBeanFactory
   ConfigurableListableBeanFactory beanFactory = getBeanFactory();
  //DefaultListBeanFactory does not create messageSource
   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.isDebugEnabled()) {
         logger.debug("Using MessageSource [" + this.messageSource + "]");
      }
   }
   

// Now go to create entity class  
 else {
      // Use empty MessageSource to be able to accept getMessage calls.
      DelegatingMessageSource dms = new DelegatingMessageSource();
      dms.setParentMessageSource(getInternalParentMessageSource());
      this.messageSource = dms;
      //注册messageRource
      registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
public void registerSingleton(String beanName, Object singletonObject) throws IllegalStateException {
   super.registerSingleton(beanName, singletonObject);

   if (hasBeanCreationStarted()) {
      // Cannot modify startup-time collection elements anymore (for stable iteration)
      synchronized (this.beanDefinitionMap) {
         if (!this.beanDefinitionMap.containsKey(beanName)) {
            Set<String> updatedSingletons = new LinkedHashSet<String>(this.manualSingletonNames.size() + 1);
            updatedSingletons.addAll(this.manualSingletonNames);
            updatedSingletons.add(beanName);
            this.manualSingletonNames = updatedSingletons;
         }
      }
   }
   else {
      // Still in startup registration phase
      if (!this.beanDefinitionMap.containsKey(beanName)) {
         this.manualSingletonNames.add(beanName);
      }
   }

   clearByTypeCache ();
}
if (logger.isDebugEnabled()) {
         logger.debug("Unable to locate MessageSource with name '" + MESSAGE_SOURCE_BEAN_NAME +
               "': using default [" + this.messageSource + "]");
      }
   }
}

Until the initialization of the MessageResource class is completed

3. Initialize the ApplicationEventMulticaster subclass (this class and subclasses are the listener management classes, responsible for the event publishing of various ApplicationListeners, etc.)

protected void initApplicationEventMulticaster() {
   ConfigurableListableBeanFactory beanFactory = getBeanFactory();
   // Whether various judgments are included in the existing bean collection
public boolean containsLocalBean(String name) {
   String beanName = transformedBeanName(name);
   return ((containsSingleton(beanName) || containsBeanDefinition(beanName)) &&
         (!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(beanName)));
}
if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
      this.applicationEventMulticaster =
            beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
      if (logger.isDebugEnabled()) {
         logger.debug("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
      }
   }
   else {  
      // create one if not
      this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
      //register to beanFactory
      beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
      if (logger.isDebugEnabled()) {
         logger.debug("Unable to locate ApplicationEventMulticaster with name '" +
               APPLICATION_EVENT_MULTICASTER_BEAN_NAME +
               "': using default [" + this.applicationEventMulticaster + "]");
      }
   }
}

4. onRefresh method:

protected void onRefresh() {
   this.themeSource = UiApplicationContextUtils.initThemeSource(this);
}

 

public static ThemeSource initThemeSource(ApplicationContext context) {
      if (context.containsLocalBean(THEME_SOURCE_BEAN_NAME)) {
         ThemeSource themeSource = context.getBean(THEME_SOURCE_BEAN_NAME, ThemeSource.class);
         // Make ThemeSource aware of parent ThemeSource.
         if (context.getParent() instanceof ThemeSource && themeSource instanceof HierarchicalThemeSource) {
            HierarchicalThemeSource hts = (HierarchicalThemeSource) themeSource;
            if (hts.getParentThemeSource() == null) {
               // Only set parent context as parent ThemeSource if no parent ThemeSource
               // registered already.
               hts.setParentThemeSource((ThemeSource) context.getParent());
            }
         }
         if (logger.isDebugEnabled()) {
            logger.debug("Using ThemeSource [" + themeSource + "]");
         }
         return themeSource;
      }
      else {
         // Use default ThemeSource to be able to accept getTheme calls, either
         // delegating to parent context's default or to local ResourceBundleThemeSource.
         HierarchicalThemeSource themeSource = null;
         if (context.getParent() instanceof ThemeSource) {
            themeSource = new DelegatingThemeSource();
            themeSource.setParentThemeSource((ThemeSource) context.getParent());
         }
         else {
           //Create a new ThemeSource without it 
           themeSource = new ResourceBundleThemeSource();
         }
         if (logger.isDebugEnabled()) {
            logger.debug("Unable to locate ThemeSource with name '" + THEME_SOURCE_BEAN_NAME +
                  "': using default [" + themeSource + "]");
         }
         return themeSource;
      }
   }

}

 

Is to set a ThemeSource object. . . onRefresh method

5, registerListeners method

public Collection<ApplicationListener<?>> getApplicationListeners() {
   return this.applicationListeners;
}
protected void registerListeners() {
   // Register statically specified listeners first.
   //Get the listener instantiated in the project
   for (ApplicationListener<?> listener : getApplicationListeners()) {
      //Get the ApplicationEventMulticaster object and then manage the ApplicationListener through it, that is, add, delete, publish events, etc. For events, the professional point is multicasting, and the dialect is to traverse the held list and publish all the ApplicationListener events.

      getApplicationEventMulticaster().addApplicationListener(listener);
   }

   // Do not initialize FactoryBeans here: We need to leave all regular beans
   // uninitialized to let post-processors apply to them!
   //Get the instance names of all ApplicationListener types in the factory to instantiate one by one and call getBeanManesForType of DefaultListBeanFactory
   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);
      }
   }
}

6. There is no initial work left in the finishBeanFactoryInitialization method.

protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
   // Initialize conversion service for this context.
   if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
         beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
      beanFactory.setConversionService(
            beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
   }

   // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
   String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
   for (String weaverAwareName : weaverAwareNames) {
      getBean(weaverAwareName);
   }

   // Stop using the temporary ClassLoader for type matching.
   beanFactory.setTempClassLoader(null);

   // Allow for caching all bean definition metadata, not expecting further changes.
   beanFactory.freezeConfiguration();

   // Instantiate all remaining (non-lazy-init) singletons.
   beanFactory.preInstantiateSingletons();
}
public void preInstantiateSingletons() throws BeansException {
   if (this.logger.isDebugEnabled()) {
      this.logger.debug("Pre-instantiating singletons in " + this);
   }

   // Iterate over a copy to allow for init methods which in turn register new bean definitions.
   // While this may not be part of the regular factory bootstrap, it does otherwise work fine.
   List<String> beanNames = new ArrayList<String>(this.beanDefinitionNames);

   // Trigger initialization of all non-lazy singleton beans...
   for (String beanName: beanNames) {
      RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
      if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
         if (isFactoryBean (beanName)) {
            final FactoryBean<?> factory = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
            boolean isEagerInit;
            if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
               isEagerInit = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
                  @Override
                  public Boolean run() {
                     return ((SmartFactoryBean<?>) factory).isEagerInit();
                  }
               }, getAccessControlContext());
            }
            else {
               isEagerInit = (factory instanceof SmartFactoryBean &&
                     ((SmartFactoryBean<?>) factory).isEagerInit());
            }
            if (isEagerInit) {
               getBean (beanName);
            }
         }
         else {
            getBean (beanName);
         }
      }
   }

   // Trigger post-initialization callback for all applicable beans...
   for (String beanName: beanNames) {
      Object singletonInstance = getSingleton(beanName);
      if (singletonInstance instanceof SmartInitializingSingleton) {
         final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
         if (System.getSecurityManager() != null) {
            AccessController.doPrivileged(new PrivilegedAction<Object>() {
               @Override
               public Object run() {
                  smartSingleton.afterSingletonsInstantiated();
                  return null;
               }
            }, getAccessControlContext());
         }
         else {
            smartSingleton.afterSingletonsInstantiated();
         }
      }
   }


}

 

7、finishRefresh

 

protected void finishRefresh() {
   // Initialize lifecycle processor for this context.
   initLifecycleProcessor();
protected void initLifecycleProcessor() {
   ConfigurableListableBeanFactory beanFactory = getBeanFactory();
   //If there is an existing lifecycleProcessor, copy it to the factory's lifecycleProcessor
   if (beanFactory.containsLocalBean(LIFECYCLE_PROCESSOR_BEAN_NAME)) {
      this.lifecycleProcessor =
            beanFactory.getBean(LIFECYCLE_PROCESSOR_BEAN_NAME, LifecycleProcessor.class);
      if (logger.isDebugEnabled()) {
         logger.debug("Using LifecycleProcessor [" + this.lifecycleProcessor + "]");
      }
   }
   else {
     //If not, create a DefaultLifecycleProcessor and copy it to the lifecycleProcessor of the factory class
      DefaultLifecycleProcessor defaultProcessor = new DefaultLifecycleProcessor();
      defaultProcessor.setBeanFactory(beanFactory);
      this.lifecycleProcessor = defaultProcessor;
      beanFactory.registerSingleton(LIFECYCLE_PROCESSOR_BEAN_NAME, this.lifecycleProcessor);
      if (logger.isDebugEnabled()) {
         logger.debug("Unable to locate LifecycleProcessor with name '" +
               LIFECYCLE_PROCESSOR_BEAN_NAME +
               "': using default [" + this.lifecycleProcessor + "]");
      }
   }
}
// Propagate refresh to lifecycle processor first.
   // Get the previous lifecycleProcessor to refresh
   getLifecycleProcessor().onRefresh();
  
 
lifecycleProcessor
public void onRefresh() {
   startBeans (true);
private void startBeans(boolean autoStartupOnly) {
    //Get the subclass of Lifecycle.class
   Map<String, Lifecycle> lifecycleBeans = getLifecycleBeans();
 
protected Map<String, Lifecycle> getLifecycleBeans() {
   Map<String, Lifecycle> beans = new LinkedHashMap<String, Lifecycle>();
   String[] beanNames = this.beanFactory.getBeanNamesForType(Lifecycle.class, false, false);
   for (String beanName: beanNames) {
      String beanNameToRegister = BeanFactoryUtils.transformedBeanName (beanName);
      boolean isFactoryBean = this.beanFactory.isFactoryBean(beanNameToRegister);
      String beanNameToCheck = (isFactoryBean? BeanFactory.FACTORY_BEAN_PREFIX + beanName: beanName);
      if ((this.beanFactory.containsSingleton(beanNameToRegister) &&
            (!isFactoryBean || Lifecycle.class.isAssignableFrom(this.beanFactory.getType(beanNameToCheck)))) ||
            SmartLifecycle.class.isAssignableFrom(this.beanFactory.getType(beanNameToCheck))) {
         Lifecycle bean = this.beanFactory.getBean(beanNameToCheck, Lifecycle.class);
         if (bean != this) {
            beans.put(beanNameToRegister, bean);
         }
      }
   }
Map<Integer, LifecycleGroup> phases = new HashMap<Integer, LifecycleGroup>();
   for (Map.Entry<String, ? extends Lifecycle> entry : lifecycleBeans.entrySet()) {
      Lifecycle bean = entry.getValue();
      if (!autoStartupOnly || (bean instanceof SmartLifecycle && ((SmartLifecycle) bean).isAutoStartup())) {
         int phase = getPhase(bean);
         LifecycleGroup group = phases.get(phase);
         if (group == null) {
            group = new LifecycleGroup(phase, this.timeoutPerShutdownPhase, lifecycleBeans, autoStartupOnly);
            phases.put(phase, group);
         }
         group.add(entry.getKey(), bean);
      }
   }
   if (phases.size() > 0) {
      List<Integer> keys = new ArrayList<Integer>(phases.keySet());
      Collections.sort(keys);
      for (Integer key : keys) {
         phases.get(key).start();
      }
   }
}
this.running = true;
}
   

   // Publish the final event.
   publishEvent(new ContextRefreshedEvent(this));

   // Participate in LiveBeansView MBean, if active.
   LiveBeansView.registerApplicationContext(this);
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326928451&siteId=291194637