Spring Boot 启动过程源码剖析

Posted by Vincent on November 30, 2020

Spring Boot 启动过程

其实整个 spring boot的启动过程,目标都是为了实例化 application context

  • new SpringApplication
    • 确定实例化的 application context的类型
      • 用classloaderclass去看是否能load到对应的 load到就代表配置了,load不到就代表没配置
      • 有3种类型
        • None
        • Servlet
        • REACTIVE
    • get application context initializer
      • load META–inf/spring. factories:从jar包里面找到所有的 spring.factories
      • 从里面取出key (interface) 为org.springframework.context.ApplicationContextInitializer的class
      • 实例化,并加入到ApplicationContext里面
    • get application listener
      • 从上一步的cache里面取出key (interface) 为org. springframework.context.ApplicationListener的class
      • 实例化,并加入到ApplicationContext里面
    • 找到main class
      • 这里用到了一个比较tricky的方法。为了找到main class,它先是new了一个RuntimeException,然后 getStackTrace,然后forloop找到 method name是”main”的StackTraceElement,最后拿到它的 class name
      • 不过这里有个不懂的地方,因为我们已经传入了 primarySources,而这个正是 main method存在的class,不懂为什么不直接用这个。
  • run(args)
    • new SpringApplicationRunListeners()
      • 从cache里面取出key (interface) 为org. springframework.boot.SpringApplicationRunListener的class
      • 实例化,并作为listeners参数来new SpringApplicationRunListeners
    • 广播starting event
      • forloop SpringApplicationRunListener里面的listener,调用他们的starting()
        • 里面其实就是在广播 ApplicationStartingEvent