Spring 启动过程(下)

简介: Spring 是我们最常用的框架之一,我们今天一起来带大家一些探究一下 Spring 的启动过程。 首先,Spring 的启动过程分为 12 个步骤主要是完成容器的初始化,以及对单实例非懒加载 Bean 完成创建和Bean 属性的赋值注入和初始化,以及消息派发器的创建和启动过程消息的触发。 补充:本文和后续版本基于 spring-5.1.14 版本展开

4. postProcessBeanFactory(beanFactory)


  • 本方法是用来给子类实现拓展的


5. invokeBeanFactoryPostProcessors(beanFactory) 执行 BeanFactory 后置处理器


1. 获取所有的  BeanDefinitionRegistryPostProcessor
2. 先执行实现了 PriorityOrdered 优先级接口BeanDefinitionRegistryPostProcessor
3. 再执行实现了 Ordered 顺序接口的 BeanDefinitionRegistryPostProcessor
4. 最后一步执行没有实现优先级接口或者顺序的接口的 BeanDefinitionRegistryPostProcessors
5. 获取所有的 BeanFactoryPostProcessor
6. 执行实现了 PriorityOrdered 优先级接口的 BeanFactoryPostProcessor
7. 执行实现了 Ordered 顺序接口的 BeanFactoryPostProcessor
8. 执行没有实现优先级接口或者顺序的接口的 BeanFactoryPostProcessor
/**
 * 执行 BeanFactoryPostProcessors 的方法
 * @param beanFactory
 * @param beanFactoryPostProcessors
 */
public static void invokeBeanFactoryPostProcessors(
    ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
  // Invoke BeanDefinitionRegistryPostProcessors first, if any.
  Set<String> processedBeans = new HashSet<>();
  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<>();
    // 1. 获取所有的  BeanDefinitionRegistryPostProcessor
    String[] postProcessorNames =
        beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
    // 2. 先执行实现了 PriorityOrdered 优先级接口的 BeanDefinitionRegistryPostProcessor、
    //      postProcessor.postProcessBeanDefinitionRegistry(registry);
    for (String ppName : postProcessorNames) {
      if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
        currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
        processedBeans.add(ppName);
      }
    }
    sortPostProcessors(currentRegistryProcessors, beanFactory);
    registryProcessors.addAll(currentRegistryProcessors);
    invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
    currentRegistryProcessors.clear();
    // 3. 再执行实现了 Ordered 顺序接口的 BeanDefinitionRegistryPostProcessor
    postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
    for (String ppName : postProcessorNames) {
      if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
        currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
        processedBeans.add(ppName);
      }
    }
    sortPostProcessors(currentRegistryProcessors, beanFactory);
    registryProcessors.addAll(currentRegistryProcessors);
    invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
    currentRegistryProcessors.clear();
    // 4. 最后一步执行没有实现优先级接口或者顺序的接口的 BeanDefinitionRegistryPostProcessors
    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;
        }
      }
      sortPostProcessors(currentRegistryProcessors, beanFactory);
      registryProcessors.addAll(currentRegistryProcessors);
      invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
      currentRegistryProcessors.clear();
    }
    // Now, invoke the postProcessBeanFactory callback of all processors handled so far.
    invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
    invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
  }
  else {
    // Invoke factory processors registered with the context instance.
    invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
  }
  // 再来执行 BeanFactoryPostProcess 的方法
  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);
    }
  }
  // 2. 先执行实现了 PriorityOrdered 优先级接口的 BeanFactoryPostProcessor、
  //      postProcessor.postProcessBeanFactory(beanFactory);
  sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
  invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
  // 3. 再执行实现了 Ordered 顺序接口的 BeanFactoryPostProcessor
  List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>();
  for (String postProcessorName : orderedPostProcessorNames) {
    orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
  }
  sortPostProcessors(orderedPostProcessors, beanFactory);
  invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
  // 4. 最后一步执行没有实现优先级接口或者顺序的接口的 BeanFactoryPostProcessor
  List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
  for (String postProcessorName : nonOrderedPostProcessorNames) {
    nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
  }
  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();
}


6. registerBeanPostProcessors(beanFactory) 注册 Bean 后置处理器


  • BeanPostProcessor 进行排序,排序分为三类:PriorityOrdered, Ordered,non 默认,MergedBeanDefinitionPostProcessor


  • 排序后以此存入到 priorityOrderedPostProcessors, orderedPostProcessors, nonOrderedPostProcessors,internalPostProcessors 集合中


  • 这里的优先级是: PriorityOrdered -> Ordered -> 无 -> MergedBeanDefinitionPostProcessor

     注意:如果是实现了多个接口那么则按照最低优先级作为排序的顺序


  • 按照顺序注册后置处理器


  • 最后注册一个 ApplicationListenerDetector 到容器中


public static void registerBeanPostProcessors(
    ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
  // 1. 获取所有的 BeanPostProcessor; 后置处理器都可以通过 PriorityOrdered、Ordered 接口来指定优先级
  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) {
    if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {// PriorityOrdered @Order @Priority
      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);
    }
  }
  // 2. 先注册 PriorityOrdered 优先级接口的 BeanPostProcessors
  sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
  registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
  // 3. 再注册 Order 优先级接口的 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);
  // 4. 最后注册没有任何优先级接口的 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);
  // 5. 最终注册 MergedBeanDefinitionPostProcessor
  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).
  // 6. 注册一个 ApplicationListenerDetector,来在 Bean 创建完成后检查是否是 ApplicationListener 如果是
  beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}


7. initMessageSource() 初始化 MessageSource 组件


8. initApplicationEventMulticaster() 初始化事件派发器


protected void initApplicationEventMulticaster() {
  // 1. 获取 BeanFactory
  ConfigurableListableBeanFactory beanFactory = getBeanFactory();
  // 2. 从 BeanFactory 中获取 applicationEventMulticaster 的 applicationEventMulticaster
  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 {
    // 3. 如果上一步没有配置:创建一个 SimpleApplicationEventMulticaster
    this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
    // 4. 将创建的 ApplicationEventMulticaster 添加到 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() + "]");
    }
  }
}


9. onRefresh() 预留方法,用于自定义实现重写实现特殊 Bean 的处理


10. registerListeners() 注册监听器


protected void registerListeners() {
  // Register statically specified listeners first.
  // 1. 从容器中拿到所有的 ApplicationListener 组件
  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!
  // 2. 每个监听器添加到事件派发器中
  //      getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
  // 到这一步因为 FactoryBean 还没有调用 getObject() 方法生成 Bean 对象, 所以这里要根据类型查找一下 ApplicationListener 记录对应类型
  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...
  // 3. 派发之前步骤产生的事件
  Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
  this.earlyApplicationEvents = null;
  if (earlyEventsToProcess != null) {
    for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
      getApplicationEventMulticaster().multicastEvent(earlyEvent);
    }
  }
}


11. finishBeanFactoryInitialization(beanFactory) 刷新前的预处理工作


1. 初始化单实例 Bean
2. 对属性进行赋值
和部分将在 Bean 的初始化,依赖注入,循环依赖中拓展


12. finishRefresh() 执行 Bean 的生命周期启动和时间发布


protected void finishRefresh() {
  // Clear context-level resource caches (such as ASM metadata from scanning).
  clearResourceCaches();
  // Initialize lifecycle processor for this context.
  // 2. initLifecycleProcessor(); 初始化和生命周期有关的后置处理器
  //    默认从容器中找是否有 lifecycleProcessor 的组件 【LifecycleProcessor】,如果没有就使用默认的生命周期组件
  //      new DefaultLifecycleProcessor();
  //    加入容器中方便使用
  //    LifecycleProcessor 写一个实现类 LifecycleProcessor 的实现类,可以在BeanFactory 的方法进行调用
  //      void onRefresh();
  //      void onClose();
  initLifecycleProcessor();
  // Propagate refresh to lifecycle processor first.
  // 3. 拿到生命周期处理器(BeanFactory)回调 onRefresh()),
  getLifecycleProcessor().onRefresh();
  // Publish the final event.
  // 4. publishEvent(new ContextRefreshedEvent(this)); 发布容器刷新完成事件
  publishEvent(new ContextRefreshedEvent(this));
  // Participate in LiveBeansView MBean, if active.
  // 5. LiveBeansView.registerApplicationContext(this);
  LiveBeansView.registerApplicationContext(this);
}


相关文章
|
存储 Java Spring
【Spring容器的启动过程】
【Spring容器的启动过程】
|
2月前
|
消息中间件 缓存 Java
手写模拟Spring Boot启动过程功能
【11月更文挑战第19天】Spring Boot自推出以来,因其简化了Spring应用的初始搭建和开发过程,迅速成为Java企业级应用开发的首选框架之一。本文将深入探讨Spring Boot的背景历史、业务场景、功能点以及底层原理,并通过Java代码手写模拟Spring Boot的启动过程,帮助读者深入理解其工作机制。
53 3
|
IDE 网络协议 Java
2021最新 IDEA 启动失败 & 启动Spring boot 项目端口被占用问题 彻底解决方案
2021最新 IDEA 启动失败 & 启动Spring boot 项目端口被占用问题 彻底解决方案
850 0
2021最新 IDEA 启动失败 & 启动Spring boot 项目端口被占用问题 彻底解决方案
|
5月前
|
设计模式 缓存 Java
深入Spring Boot启动过程:揭秘设计模式与代码优化秘籍
深入Spring Boot启动过程:揭秘设计模式与代码优化秘籍
|
7月前
|
监控 Java Spring
深入理解Spring Boot的启动过程
深入理解Spring Boot的启动过程
|
8月前
|
XML Java 数据格式
Spring5源码(15)-IoC容器启动过程简析及XmlBeanFactory初始化
Spring5源码(15)-IoC容器启动过程简析及XmlBeanFactory初始化
78 1
|
XML Java 数据格式
Spring的IoC容器启动过程之源码级分析
Spring的IoC容器启动过程之源码级分析
290 0
|
Java 容器 Spring
Spring Boot启动过程
Spring Boot启动过程
104 0
|
存储 XML 安全
Spring - FactoryBean扩展实战_MyBatis-Spring 启动过程源码解读
在理解 MyBatis-Spring 的启动过程时,需要重点把握的是 `SqlSessionTemplate` 核心类的设计理念及其实现过程,使用了JDK动态代理机制。
166 0
Spring - FactoryBean扩展实战_MyBatis-Spring 启动过程源码解读
|
JSON SpringCloudAlibaba 负载均衡
【微服务35】分布式事务Seata源码解析三:从Spring Boot特性来看Seata Client 启动时都做了什么
【微服务35】分布式事务Seata源码解析三:从Spring Boot特性来看Seata Client 启动时都做了什么
872 0
【微服务35】分布式事务Seata源码解析三:从Spring Boot特性来看Seata Client 启动时都做了什么