spring boot 启动流程
1.创建 SpringApplication对象
initialize(sources) 进入方法
1 private void initialize(Object[] sources) {
//判断是否为空 保存主配置类 2 if (sources != null && sources.length > 0) { 3 this.sources.addAll(Arrays.asList(sources)); 4 } 5 //判断应用是不是web应用 "javax.servlet.Servlet", "org.springframework.web.context.ConfigurableWebApplicationContext" 6 this.webEnvironment = this.deduceWebEnvironment();
//从类路径下找到 META-INF/spring.factories 配置的全部的 ApplicationContextInitializer ,然后保存在 initializers 数组对象里面 7 this.setInitializers(this.getSpringFactoriesInstances(ApplicationContextInitializer.class));
//从类路径下找到 META-INF/spring.factories 配置的全部的 ApplicationListener ,然后保存在 listeners 数组对象里面 8 this.setListeners(this.getSpringFactoriesInstances(ApplicationListener.class));
//从配置类中找到有mian方法的主配置类 9 this.mainApplicationClass = this.deduceMainApplicationClass(); 10 }
2.运行run方法
public ConfigurableApplicationContext run(String... args) { StopWatch stopWatch = new StopWatch(); //Stopwatch类提供了一种方便的机制来测量运行时间 stopWatch.start(); ConfigurableApplicationContext context = null; //IOC容器 FailureAnalyzers analyzers = null; configureHeadlessProperty();
//获取SpringApplicationRunListeners 对象 , 从类路径下找到 META-INF/spring.factories 配置的全部的 SpringApplicationRunListener , SpringApplicationRunListeners listeners = getRunListeners(args);
//回调 获取SpringApplicationRunListeners.starting()方法 listeners.starting(); try {
//封装命令行参数 ApplicationArguments applicationArguments = new DefaultApplicationArguments( args);
//准备环境 ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
//创建环境完成后 回调 SpringApplicationRunListeners.environmentPrepared();//表示环境准备完成
Banner printedBanner = printBanner(environment);
创建ApplicationContext,决定创建web的IOC,还是普通的IOC context = createApplicationContext(); analyzers = new FailureAnalyzers(context);
//准备上下文环境,将 environment 保存在IOC中,而且applyInitializers();
//applyInitializers(); 回调之前保存的全部的ApplicationContextInitializer的initialize方法
//回调全部SpringApplicationRunListener的contextPrepared()方法
//prepareContext运行完成以后回调全部的SpringApplicationRunListeners的contextLoaded()
prepareContext(context, environment, listeners, applicationArguments, printedBanner);
//刷新容器, 也是就容器初始化过程(如果是web应用还会嵌入tomact)
//扫描,创建,加在所有组件的地方,(配置类,组件,自动配置) refreshContext(context);
//从IOC容器中获取所有 ApplicationRunner和CommandLineRunner进行回调
//ApplicationRunner先回调 CommandLineRunner在回调
afterRefresh(context, applicationArguments);
//所有的SpringApplicationRunListener回调finished方法 listeners.finished(context, null); stopWatch.stop(); if (this.logStartupInfo) { new StartupInfoLogger(this.mainApplicationClass) .logStarted(getApplicationLog(), stopWatch); }
//整个springBoot应用启动完成以后返回启动的IOC容器 return context; } catch (Throwable ex) { handleRunFailure(context, listeners, analyzers, ex); throw new IllegalStateException(ex); } }
不开心过一天,开心过一天,何不开开心心每一天