一、整体流程分析
- 使用构造方法 SpringApplication 初始化一些数据
- 初始化 webApplicationType,指定web类型,一般是servlet
- setInitializers 设置初始化类 ApplicationContextInitializer 到List
- 内部调用 getSpringFactoriesInstances 方法从 spring.factories 文件中获取 ApplicationContextInitializer下的所有类
- setListeners 设置监听器 ApplicationContextInitializer 到 List
- 内部调用 getSpringFactoriesInstances 方法从 spring.factories 文件中获取 ApplicationContextInitializer下的所有类
- Class._forName 加载主类启动器,即 _SpringBoot04Application.class
- 执行 SpringApplication().run() 中的run方法
- 设置启动时间、系统属性、环境参数、忽略bean的配置、banner、webApplicationType、异常报告器类型
- prepareContext 给应用上下文对象中设置一系列的属性值 (环境对象、初始化参数、发布监听事件、创建bean工厂)
- refreshContext 重写Spring的refresh方法,初始化bean的一些信息
- SpringApplicationRunListeners 启动
- callRunners �执行一些继承了 ApplicationRunner 和 CommandLineRunner 的方法
- SpringApplicationRunListeners 运行。
二、源码剖析
1、new SpringApplication(primarySources)
进入run方法后如下public class SpringBoot04Application {public static void main(String[] args) {SpringApplication.run(SpringBoot04Application.class, args);}}
进入构造方法SpringApplication ```java Listpublic static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {return new SpringApplication(primarySources).run(args);}
> initializers; List > listeners;
public SpringApplication(ResourceLoader resourceLoader, Class<?>… primarySources) {
this.resourceLoader = resourceLoader;Assert.notNull(primarySources, "PrimarySources must not be null");// primarySources 就是 SpringBoot04Applicationthis.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));// 决定用哪个 WebApplicationType,这里是 servletthis.webApplicationType = WebApplicationType.deduceFromClasspath();// 实例化初始化类,这里初始化的是 spring.factories 文件里面的 ApplicationContextInitializer 下面的对象setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));// 实例化监听器,这里初始化的是 spring.factories 文件里面的 ApplicationListener 下面的对象setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));// 加载主类 即 SpringBoot04Application 到 JVN 内存中this.mainApplicationClass = deduceMainApplicationClass();}
<a name="YhrjI"></a>### 1.1 getSpringFactoriesInstances```java// 这里的type就是 spring.factories 里面的等号左边的类名private <T> Collection<T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object... args) {ClassLoader classLoader = getClassLoader();// Use names and ensure unique to protect against duplicates// 从 spring.factories 中读取 指定的type下的类名Set<String> names = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(type, classLoader));// 根据全类名反射实例化 ctor.newInstanceList<T> instances = createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);// 排序AnnotationAwareOrderComparator.sort(instances);return instances;}
1.1.1 SpringFactoriesLoader.loadFactoryNames
�从 spring.factories 中读取 指定的type下的类名
public static List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) {String factoryTypeName = factoryType.getName();// loadSpringFactories 用于读取 spring.factories 所有的类名,并存如cache中// getOrDefault 获取指定的类名return (List)loadSpringFactories(classLoader).getOrDefault(factoryTypeName, Collections.emptyList());}
1.2 deduceMainApplicationClass
private Class<?> deduceMainApplicationClass() {try {StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();for (StackTraceElement stackTraceElement : stackTrace) {if ("main".equals(stackTraceElement.getMethodName())) {return Class.forName(stackTraceElement.getClassName());}}}catch (ClassNotFoundException ex) {// Swallow and continue}return null;}
2、new SpringApplication(primarySources).run(args)
public ConfigurableApplicationContext run(String... args) {StopWatch stopWatch = new StopWatch();stopWatch.start();ConfigurableApplicationContext context = null;Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();// 设置一些系统属性configureHeadlessProperty();// 获取监听器:即在spring.factories中配置在 SpringApplicationRunListener 里的类(实现了接口SpringApplicationRunListener)SpringApplicationRunListeners listeners = getRunListeners(args);listeners.starting();try {ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);// 提前准备一些环境参数ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);// 读取需要忽略bean的配置configureIgnoreBeanInfo(environment);// 读取banner信息Banner printedBanner = printBanner(environment);// 根据 webApplicationType 创建对应的 加载并实例化对应的上下文对象(AnnotationConfigServletWebServerApplicationContext)context = createApplicationContext();// 获取 spring.factories 文件里面的 SpringBootExceptionReporter 下面的对象exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,new Class[] { ConfigurableApplicationContext.class }, context);// 上下文对象中设置一系列的属性值prepareContext(context, environment, listeners, applicationArguments, printedBanner);// 内部调用 Spring 的refresh 方法,与Spring整合refreshContext(context);afterRefresh(context, applicationArguments);stopWatch.stop();if (this.logStartupInfo) {new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);}// 监听器执行listeners.started(context);// 执行一些继承了 ApplicationRunner 和 CommandLineRunner 的方法callRunners(context, applicationArguments);}catch (Throwable ex) {handleRunFailure(context, ex, exceptionReporters, listeners);throw new IllegalStateException(ex);}try {// Springboot启动listeners.running(context);}catch (Throwable ex) {handleRunFailure(context, ex, exceptionReporters, null);throw new IllegalStateException(ex);}return context;}
2.1 prepareContext
上下文对象中设置一系列的属性值 (环境对象、初始化参数、发布监听事件、创建bean工厂)
private void prepareContext(ConfigurableApplicationContext context, ConfigurableEnvironment environment,SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments, Banner printedBanner) {context.setEnvironment(environment);// 添加一些 post processing 到 context 中postProcessApplicationContext(context);// 在所有的初始化器中添加 context(initializer.initialize(context);)applyInitializers(context);// 在所有的监听器中添加 context到对应的事件中 (listener.contextPrepared(context);)listeners.contextPrepared(context);if (this.logStartupInfo) {logStartupInfo(context.getParent() == null);logStartupProfileInfo(context);}// Add boot specific singleton beans// 获取spring的bean工厂,这里默认是DefaultListableBeanFactoryConfigurableListableBeanFactory beanFactory = context.getBeanFactory();beanFactory.registerSingleton("springApplicationArguments", applicationArguments);// beanFactory 的一些信息的设置if (printedBanner != null) {beanFactory.registerSingleton("springBootBanner", printedBanner);}if (beanFactory instanceof DefaultListableBeanFactory) {((DefaultListableBeanFactory) beanFactory).setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);}if (this.lazyInitialization) {context.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor());}// Load the sourcesSet<Object> sources = getAllSources();Assert.notEmpty(sources, "Sources must not be empty");// 如果包含了 @Component 注解,则将启动类注册到 AnnotatedBeanDefinitionReader 中load(context, sources.toArray(new Object[0]));// 监听器,发布事件 (listeners.contextLoaded(context))listeners.contextLoaded(context);}
2.1.1 load
如果包含了 @Component 注解,则将启动类注册到 AnnotatedBeanDefinitionReader 中,即将类添加到BeanFactory中,这里就是将主类添加到BeanFactory
private final AnnotatedBeanDefinitionReader annotatedReader;// Load beans into the application context.private int load(Class<?> source) {if (isGroovyPresent() && GroovyBeanDefinitionSource.class.isAssignableFrom(source)) {// Any GroovyLoaders added in beans{} DSL can contribute beans hereGroovyBeanDefinitionSource loader = BeanUtils.instantiateClass(source, GroovyBeanDefinitionSource.class);load(loader);}if (isComponent(source)) {// 如果包含了 @Component 注解,则将启动类注册到 AnnotatedBeanDefinitionReader 中this.annotatedReader.register(source);return 1;}return 0;}
2.2 refreshContext
内部调用了 Spring的refresh方法。Spring内部的refresh方法,这里不做过多介绍,具体参回顾:
5、Spring IOC 容器和对象的创建流程
1、prepareRefresh
2、obtainFreshBeanFactory
在Spring中,这个方法会创建一个默认的BeanFactory,但是在Springboot中,由于 prepareContext中已经创建了BeanFactory了,所以这里拿到的是Springboot创建的BeanFactory。
3、prepareBeanFactory
4、postProcessBeanFactory
�在beanFactory中设置一些SpringBoot相关的BeanPostProcessor(addBeanPostProcessor)
Spring里面的这个方法是空的
5、invokeBeanFactoryPostProcessors
执行 BeanFactoryPostProcessors,即 实现了接口 BeanFactoryPostProcessor 的一些类。
6、registerBeanPostProcessors
注册 BeanPostProcessors 相关内容( 实现了 接口 BeanPostProcessors 的一些方法),添加到beanFactory中—》beanFactory.addBeanPostProcessor
7、�initMessageSource()
为上下文初始化 message原,即不同语言的消息体,国际化操作。
8、initApplicationEventMulticaster()
初始化事件监听多路广播器
onRefresh();留给子类初始化其他的bean
�registerListeners();在所有注册的bean中查找listener bean,注册到消息广播器中。
9、onRefresh
Spring里面的这个方法是空的
Springboot 在这里创建Tomcat
@Overrideprotected void onRefresh() {super.onRefresh();try {createWebServer();}catch (Throwable ex) {throw new ApplicationContextException("Unable to start web server", ex);}}
10、registerListeners
在所有注册的bean(即实现了接口 ApplicationListener 的一些方法)中查找listener bean,注册到消息广播器中
11、finishBeanFactoryInitialization
通过 方法 finishBeanFactoryInitialization() 初始化所有非懒加载的单例对象。
2.3 callRunners
�执行一些继承了 ApplicationRunner 和 CommandLineRunner 的方法
2.4 listeners.running(context)
启动Spring.factories中的方法(org.springframework.boot.SpringApplicationRunListener下的一些方法)
�
�
