SpringApplication run方法解析
public ConfigurableApplicationContext run(String... args) { StopWatch stopWatch = new StopWatch(); stopWatch.start(); ConfigurableApplicationContext context = null; FailureAnalyzers analyzers = null; configureHeadlessProperty(); //1.创建了应用的监听器SpringApplicationRunListeners并开始监听 SpringApplicationRunListeners listeners = getRunListeners(args); listeners.starting(); try { //2.创建⼀个DefaultApplicationArguments对象,它持有着args参数,就是main函数传进来的参数.调⽤prepareEnvironment⽅法 ApplicationArguments applicationArguments = new DefaultApplicationArguments( args); //3.加载SpringBoot配置环境(ConfigurableEnvironment),如果是通过web容器发布,会加载StandardEnvironment ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments); //4.打印banner Banner printedBanner = printBanner(environment); //5.创建run方法的返回对象:ConfigurableApplicationContext(应用配置上下文) context = createApplicationContext(); analyzers = new FailureAnalyzers(context); //6.回到run方法内,prepareContext方法将listeners、environment、applicationArguments、banner等重 //要组件与上下文对象关联 prepareContext(context, environment, listeners, applicationArguments, printedBanner); //7.接下来的refreshContext(context)方法(初始化方法如下)将是实现spring-boot-starter-*(mybatis、 //redis等)自动化配置的关键,包括spring.factories的加载,bean的实例化等核心工作。 refreshContext(context); afterRefresh(context, applicationArguments); listeners.finished(context, null); stopWatch.stop(); return context; } catch (Throwable ex) { handleRunFailure(context, listeners, analyzers, ex); throw new IllegalStateException(ex); } }
Servlet启动原理
----------------------------------创建IOC容器---------------------------
1 spring boot 应用启动运行run方法
2 createApplicationContext():创建IOC容器,如果是web应用则创建AnnotationConfigEmbeddedWebApplacation的IOC容器,如果不是,则创建AnnotationConfigApplication的IOC容器
3 refreshContext(context)->refresh(context)->调用父类的refresh()的方法刷新刚才创建的IOC容器
(并初始化容器,创建容器每一个组件)
----------------------------------创建Servlet容器---------------------------
4 抽象父类AbstractApplicationContext类的子类EmbeddedWebApplicationContext的onRefresh方法
5 在createEmbeddedServletContainer会获取嵌入式Servlet容器工厂,由容器工厂创建Servlet
6 从IOC容器中获取Servlet容器工厂
7 使用Servlet容器工厂获取嵌入式Servlet容器,具体使用哪一个容器工厂看配置环境依赖
8 上述创建过程 首先启动IOC容器,接着启动嵌入式Servlet容器,接着将IOC容器中剩下没有创建的对象获取出来,比如自己创建的controller