Spring 启动记录(12)

1、等到spring的refresh方法到registerBeanPostProcessors

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

跟之前的BeanProcessorFactory注册的流程一样

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、等到BeanProcessor初始化完成后执行initMessageSource

protected void initMessageSource() {
   //此处得到的是DefaultListBeanFactory
   ConfigurableListableBeanFactory beanFactory = getBeanFactory();
  //DefaultListBeanFactory是没有创建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 + "]");
      }
   }
   

// 此时走创建实体类  
 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 + "]");
      }
   }
}

至此次MessageResource类初始化完成

3、初始化ApplicationEventMulticaster子类(这个类及子类是监听器的管理类,负责各种ApplicationListener的事件发布等)

protected void initApplicationEventMulticaster() {
   ConfigurableListableBeanFactory beanFactory = getBeanFactory();
   //各种判断是否包含在已有的bean集合中
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 { 
      //没有则创建一个
      this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
      //注册到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 方法:

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 {
           //没有就新建一个ThemeSource
            themeSource = new ResourceBundleThemeSource();
         }
         if (logger.isDebugEnabled()) {
            logger.debug("Unable to locate ThemeSource with name '" + THEME_SOURCE_BEAN_NAME +
                  "': using default [" + themeSource + "]");
         }
         return themeSource;
      }
   }

}

就是设置了一个ThemeSource对象。。。onRefresh方法

5、registerListeners 方法

public Collection<ApplicationListener<?>> getApplicationListeners() {
   return this.applicationListeners;
}
protected void registerListeners() {
   // Register statically specified listeners first.
   //获取工程中实例化的监听器
   for (ApplicationListener<?> listener : getApplicationListeners()) {
      //获取ApplicationEventMulticaster对象然后通过它管理ApplicationListener,即添加,删除,发布事件等,对于事件来说专业点就是多路广播,土话就是遍历持有的list,发布所以的ApplicationListener事件

      getApplicationEventMulticaster().addApplicationListener(listener);
   }

   // Do not initialize FactoryBeans here: We need to leave all regular beans
   // uninitialized to let post-processors apply to them!
   //获取到工厂内所有ApplicationListener类型的实例名称逐一实例化及调用DefaultListBeanFactory的getBeanManesForType
   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、finishBeanFactoryInitialization方法初始剩余没有初始的工作

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();
   //如果有已经存在的lifecycleProcessor则复制给工厂的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 {
     //没有则创建一个DefaultLifecycleProcessor复制给工厂类的lifecycleProcessor
      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.
   //获取到刚才的lifecycleProcessor进行刷新
   getLifecycleProcessor().onRefresh();
  
 
lifecycleProcessor
public void onRefresh() {
   startBeans(true);
private void startBeans(boolean autoStartupOnly) {
   //获取到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);
}

猜你喜欢

转载自my.oschina.net/u/867830/blog/827883