1 启动配置原理
1.1 创建SpringApplication对象
@SuppressWarnings({ "unchecked", "rawtypes" }) private void initialize(Object[] sources) { //保存主配置类 if (sources != null && sources.length > 0) { this.sources.addAll(Arrays.asList(sources)); } //判断当前是否是一个web应用 this.webEnvironment = deduceWebEnvironment(); //从类路径下找到META‐INF/spring.factories配置的所有ApplicationContextInitializer然后保存起来 setInitializers((Collection) getSpringFactoriesInstances( ApplicationContextInitializer.class)); //从类路径下找到META‐INF/spring.factories配置的所有ApplicationListener然后保存起来 setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class)); //从多个配置类中找到有main方法的主配置类 this.mainApplicationClass = deduceMainApplicationClass(); }
1.2 运行run方法
public ConfigurableApplicationContext run(String... args) { StopWatch stopWatch = new StopWatch(); stopWatch.start(); ConfigurableApplicationContext context = null; FailureAnalyzers analyzers = null; configureHeadlessProperty(); //获取SpringApplicationRunListeners,从类路径下找到META‐INF/spring.factories配置的所有SpringApplicationRunListeners SpringApplicationRunListeners listeners = getRunListeners(args); //回调所有的获取SpringApplicationRunListeners.starting();方法 listeners.starting(); try { //封装命令行参数 ApplicationArguments applicationArguments = new DefaultApplicationArguments( args); //准备环境 创建环境完成后回调SpringApplicationRunListener的environmentPrepared()方法,表示环境准备完成 ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments); Banner printedBanner = printBanner(environment); //创建ApplicationContext,决定创建web的IOC容器还是普通的IOC容器 context = createApplicationContext(); analyzers = new FailureAnalyzers(context); //准备上下文环境 //将environment保存到ioc容器中; //applyInitializers(context); 回调之前报错的所有的ApplicationContextInitializer的initialize方法 //回调所有的SpringApplicationRunListener的contextPrepared()方法 //listeners.contextLoaded(context); 回调所有的SpringApplicationRunListener的contextLoaded方法 prepareContext(context, environment, listeners, applicationArguments, printedBanner); //刷新容器:IOC容器初始化流程。 refreshContext(context); //从IOC容器中获取所有的ApplicationRunner和CommandLineRunner进行回调 //ApplicationRunner先回调 //CommandLineRunner再回调 afterRefresh(context, applicationArguments); //所有的SpringApplicationRunListene回调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); } }
- 总结:
- ApplicationContextInitializer和SpringApplicationRunListener需要配置在META‐INF/spring.factories中。
- ApplicationRunner和CommandLineRunner需要放在IOC容器中。
2 自定义starter
xx
原文地址:https://www.cnblogs.com/xuweiweiwoaini/p/12272538.html
时间: 2024-10-09 06:47:43