什么时候创建嵌入式的Servlet容器工厂?什么时候获取嵌入式的Servlet容器并启动Tomcat?

    1、Spring Boot应用启动运行run方法

    2、refreshContext(context):Spring Boot刷新IOC容器(创建IOC容器对象,并初始化容器,创建容器中的每一个组件)。如果是web应用则创建AnnotationConfigEmbeddedWebApplicationContext,如果不是web应用则创建AnnotationConfigApplicationContext

    3、refresh(context):刷新刚才创建好的IOC容器

    1. public void refresh() throws BeansException, IllegalStateException {
    2. synchronized (this.startupShutdownMonitor) {
    3. // Prepare this context for refreshing.
    4. prepareRefresh();
    5. // Tell the subclass to refresh the internal bean factory.
    6. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
    7. // Prepare the bean factory for use in this context.
    8. prepareBeanFactory(beanFactory);
    9. try {
    10. // Allows post-processing of the bean factory in context subclasses.
    11. postProcessBeanFactory(beanFactory);
    12. // Invoke factory processors registered as beans in the context.
    13. invokeBeanFactoryPostProcessors(beanFactory);
    14. // Register bean processors that intercept bean creation.
    15. registerBeanPostProcessors(beanFactory);
    16. // Initialize message source for this context.
    17. initMessageSource();
    18. // Initialize event multicaster for this context.
    19. initApplicationEventMulticaster();
    20. // Initialize other special beans in specific context subclasses.
    21. onRefresh();
    22. // Check for listener beans and register them.
    23. registerListeners();
    24. // Instantiate all remaining (non-lazy-init) singletons.
    25. finishBeanFactoryInitialization(beanFactory);
    26. // Last step: publish corresponding event.
    27. finishRefresh();
    28. } catch (BeansException ex) {
    29. if (logger.isWarnEnabled()) {
    30. logger.warn("Exception encountered during context initialization - " +
    31. "cancelling refresh attempt: " + ex);
    32. }
    33. // Destroy already created singletons to avoid dangling resources.
    34. destroyBeans();
    35. // Reset 'active' flag.
    36. cancelRefresh(ex);
    37. // Propagate exception to caller.
    38. throw ex;
    39. } finally {
    40. // Reset common introspection caches in Spring's core, since we
    41. // might not ever need metadata for singleton beans anymore...
    42. resetCommonCaches();
    43. }
    44. }
    45. }

    4、onRefresh():web的ioc容器重写了onRefresh方法

    5、web ioc容器会创建嵌入式的Servlet容器,createEmbeddedServletContainer()

    6、获取嵌入式的Servlet容器工厂:
    EmbeddedServletContainerFactory containerFactory = getEmbeddedServletContainerFactory()
    从ioc容器中获取EmbeddedServletContainerFactory组件,TomcatEmbeddedServletContainerFactory创建对象,后置处理器一看是这个对象,就获取所有的定制器来先定制Servlet容器的相关配置。

    7、使用容器工厂获取嵌入式的Servlet容器:this.embeddedServletContainer = containerFactory .getEmbeddedServletContainer(getSelfInitializer())

    8、嵌入式的Servlet容器创建对象并启动Servlet容器,先启动嵌入式的Servlet容器,再将ioc容器中剩下没有创建出的对象获取出来。

    IOC容器启动创建嵌入式的Servlet容器