一、启动流程

1. 入口

SpringBoot的启动流程为boot项目中的入口main方法,然后调用SpringApplication对象的run()方法,感觉很神奇,一个main 方法解决了所有的问题,其实际底层进行了很多调用:

  1. @SpringBootApplication
  2. public class DavinciServerApplication {
  3. public static void main(String[] args) {
  4. SpringApplication.run(DavinciServerApplication.class, args);
  5. }
  6. }

进行跟进到SpringApplication 类中的run()方法,先可以看到对SpringApplication类的解释

  1. * Class that can be used to bootstrap and launch a Spring application from a Java main
  2. * method. By default class will perform the following steps to bootstrap your
  3. * application:
  4. *
  5. * <ul>
  6. * <li>Create an appropriate {@link ApplicationContext} instance (depending on your
  7. * classpath)</li>
  8. * <li>Register a {@link CommandLinePropertySource} to expose command line arguments as
  9. * Spring properties</li>
  10. * <li>Refresh the application context, loading all singleton beans</li>
  11. * <li>Trigger any {@link CommandLineRunner} beans</li>
  12. * </ul>
  13. *
  14. public class SpringApplication {
  15. // 第一步调用
  16. public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
  17. return run(new Class<?>[] { primarySource }, args);
  18. }
  19. // 第二步调用
  20. public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
  21. return new SpringApplication(primarySources).run(args);
  22. }
  23. }

从上面的解释可以看到:SpringApplication 这个类被用来引导和启动一个Spring的应用程序从一个Java 的main方法开始。默认的需要按照四个步骤来完成应用程序

  1. 创建一个 applicationContext 实例
  2. 注册一个命令行参数
  3. 重新刷新应用上下文,加载所有的单例对象
  4. 触发所有的bean对象

    2.创建SpringApplication对象

    在第一步调用run()方法的过程中,会发现最后是通过创建SpringApplication对象,然后调用该对象的run()方法,在看源码的过程中一定要注意看创建对象时构造方法的内容。SpringApplication 创建对象:
    在构造方法中会进行初始化操作。初始化时,会先进行区分环境:非web环境、web环境、reactive环境三种。如下:
    1. // 创建对象
    2. public SpringApplication(Class<?>... primarySources) {
    3. this(null, primarySources);
    4. }
    5. // 调用构造方法
    6. public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
    7. this.resourceLoader = resourceLoader;
    8. Assert.notNull(primarySources, "PrimarySources must not be null");
    9. // 初始化主要加载资源类集合并去重
    10. this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
    11. // 推断当前的WEB 应用类型,一共有三种:NONE、SERVLET、REACTIVE
    12. this.webApplicationType = WebApplicationType.deduceFromClasspath();
    13. // 设置应用上下文初始化器,从“META-INF/spring.factories”读取ApplicationContextInitializer类的实例
    14. setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
    15. // 设置监听器 从“META-INF/spring.factories”读取ApplicationListener
    16. setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
    17. this.mainApplicationClass = deduceMainApplicationClass();
    18. }
    在SpringApplication 对象初始化的过程中会有一个比较重要的步骤,就是加载读取“/META-INF”下的spring.factories文件内容,然后通过反射实例化对象,放入到缓存中。跟进代码看一下: ```java // 第一步开始调用方法 getSpringFactoriesInstances(ApplicationContextInitializer.class));

// 第二步,根据传入的类名按照key-value 的方式获取集合,并且通过反射的方式实例化所有类 private Collection getSpringFactoriesInstances(Class type, Class<?>[] parameterTypes, Object… args) { ClassLoader classLoader = getClassLoader(); // 读取配置文件数据放入集合 Set names = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(type, classLoader)); // List instances = createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names); AnnotationAwareOrderComparator.sort(instances); return instances; }

  1. <a name="tjC7V"></a>
  2. ## 3.启动
  3. SpringApplication 创建完成,初始化也完成,就开始真正的启动流程,即调用run()方法
  4. ```java
  5. public ConfigurableApplicationContext run(String... args) {
  6. // 时间监控
  7. StopWatch stopWatch = new StopWatch();
  8. stopWatch.start();
  9. ConfigurableApplicationContext context = null;
  10. Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
  11. //java.awt.headless是J2SE的一种模式用于在缺少显示屏、键盘或者鼠标时的系统配置,很多监控工具如jconsole 需要将该值设置为true,系统变量默认为true
  12. configureHeadlessProperty();
  13. //获取spring.factories中的监听器变量,args为指定的参数数组,默认为当前类SpringApplication
  14. //第一步:获取并启动监听器
  15. SpringApplicationRunListeners listeners = getRunListeners(args);
  16. listeners.starting();
  17. try {
  18. ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
  19. //第二步:构造容器环境
  20. ConfigurableEnvironment environment = prepareEnvironment(listeners,
  21. applicationArguments);
  22. //设置需要忽略的bean
  23. configureIgnoreBeanInfo(environment);
  24. //打印banner
  25. Banner printedBanner = printBanner(environment);
  26. //第三步:创建容器
  27. context = createApplicationContext();
  28. //第四步:实例化SpringBootExceptionReporter.class,用来支持报告关于启动的错误
  29. exceptionReporters = getSpringFactoriesInstances(
  30. SpringBootExceptionReporter.class,
  31. new Class[] { ConfigurableApplicationContext.class }, context);
  32. //第五步:准备容器
  33. prepareContext(context, environment, listeners, applicationArguments,
  34. printedBanner);
  35. //第六步:刷新容器
  36. refreshContext(context);
  37. //第七步:刷新容器后的扩展接口
  38. afterRefresh(context, applicationArguments);
  39. stopWatch.stop();
  40. if (this.logStartupInfo) {
  41. new StartupInfoLogger(this.mainApplicationClass)
  42. .logStarted(getApplicationLog(), stopWatch);
  43. }
  44. listeners.started(context);
  45. callRunners(context, applicationArguments);
  46. }
  47. catch (Throwable ex) {
  48. handleRunFailure(context, ex, exceptionReporters, listeners);
  49. throw new IllegalStateException(ex);
  50. }
  51. try {
  52. listeners.running(context);
  53. }
  54. catch (Throwable ex) {
  55. handleRunFailure(context, ex, exceptionReporters, null);
  56. throw new IllegalStateException(ex);
  57. }
  58. return context;
  59. }

3.1 获取并启动监听器

3.1.1 获取监听器

  1. // 第一步:获取监听器
  2. SpringApplicationRunListeners listeners = getRunListeners(args);
  3. // 继续调用创建对象时初始化的方法getSpringFactoriesInstances()
  4. // 传入的值为SpringApplicationRunListener,获取得到的对象只有一个Event
  5. private SpringApplicationRunListeners getRunListeners(String[] args) {
  6. Class<?>[] types = new Class<?>[] { SpringApplication.class, String[].class };
  7. return new SpringApplicationRunListeners(logger,
  8. getSpringFactoriesInstances(SpringApplicationRunListener.class, types, this, args));
  9. }

上面可以看到,args本身默认为空,但是在获取监听器的方法中,getSpringFactoriesInstances( SpringApplicationRunListener.class, types, this, args)将当前对象作为参数,该方法用来获取spring.factories对应的监听器:

  1. # Run Listeners
  2. org.springframework.boot.SpringApplicationRunListener=\
  3. org.springframework.boot.context.event.EventPublishingRunListener

整个 springBoot 框架中获取factories的方式统一如下:
spring-core 包里定义了 SpringFactoriesLoader 类,这个类实现了检索 META-INF/spring.factories 文件,并获取指定接口配置的功能。在这个类中定义了两个对外的方法:

loadFactories 根据接口类获取其实现类的实例,这个方法返回的是对象列表。
loadFactoryNames 根据接口获取其接口类的名称,这个方法返回的是类名的列表。

在springboot 中的SpringApplication类中有提供了一个方法获取文件内容,调用的是loadFactoryNames

  1. private <T> Collection<T> getSpringFactoriesInstances(Class<T> type) {
  2. return getSpringFactoriesInstances(type, new Class<?>[] {});
  3. }
  4. private <T> Collection<T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object... args) {
  5. ClassLoader classLoader = getClassLoader();
  6. // Use names and ensure unique to protect against duplicates
  7. Set<String> names = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
  8. List<T> instances = createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);
  9. AnnotationAwareOrderComparator.sort(instances);
  10. return instances;
  11. }

获取得到所有spring.factories文件中的配置类之后通过反射实例后返回上下文中以供使用。

  1. @SuppressWarnings("unchecked")
  2. private <T> List<T> createSpringFactoriesInstances(Class<T> type,
  3. Class<?>[] parameterTypes, ClassLoader classLoader, Object[] args,
  4. Set<String> names) {
  5. List<T> instances = new ArrayList<>(names.size());
  6. for (String name : names) {
  7. try {
  8. //装载class文件到内存
  9. Class<?> instanceClass = ClassUtils.forName(name, classLoader);
  10. Assert.isAssignable(type, instanceClass);
  11. Constructor<?> constructor = instanceClass
  12. .getDeclaredConstructor(parameterTypes);
  13. //主要通过反射创建实例
  14. T instance = (T) BeanUtils.instantiateClass(constructor, args);
  15. instances.add(instance);
  16. }
  17. catch (Throwable ex) {
  18. throw new IllegalArgumentException(
  19. "Cannot instantiate " + type + " : " + name, ex);
  20. }
  21. }
  22. return instances;
  23. }

因为SpringAppliactionRunListener.calss 对应的监听器是EventPublishingRunListener,在通过反射获取实例该类时会触发EventPublishingRunListener的构造函数:

  1. public EventPublishingRunListener(SpringApplication application, String[] args) {
  2. this.application = application;
  3. this.args = args;
  4. this.initialMulticaster = new SimpleApplicationEventMulticaster();
  5. for (ApplicationListener<?> listener : application.getListeners()) {
  6. this.initialMulticaster.addApplicationListener(listener);
  7. }
  8. }

重点来看一下addApplicationListener方法:

  1. @Override
  2. public void addApplicationListener(ApplicationListener<?> listener) {
  3. synchronized (this.retrievalMutex) {
  4. // Explicitly remove target for a proxy, if registered already,
  5. // in order to avoid double invocations of the same listener.
  6. Object singletonTarget = AopProxyUtils.getSingletonTarget(listener);
  7. if (singletonTarget instanceof ApplicationListener) {
  8. this.defaultRetriever.applicationListeners.remove(singletonTarget);
  9. }
  10. //内部类对象
  11. this.defaultRetriever.applicationListeners.add(listener);
  12. this.retrieverCache.clear();
  13. }
  14. }

上述方法定义在SimpleApplicationEventMulticaster父类AbstractApplicationEventMulticaster中。关键代码为this.defaultRetriever.applicationListeners.add(listener);,这是一个内部类,用来保存所有的监听器。也就是在这一步,将spring.factories中的监听器传递到SimpleApplicationEventMulticaster中。
继承关系如下:
image.png

3.1.2 启动监听器

listeners.starting();获取的监听器为EventPublishingRunListener,从名字可以看出是启动事件发布监听器,主要用来发布启动事件。

  1. @Override
  2. public void starting() {
  3. //关键代码,这里是创建application启动事件`ApplicationStartingEvent`
  4. this.initialMulticaster.multicastEvent(new ApplicationStartingEvent(this.application, this.args));
  5. }

EventPublishingRunListener这个是springBoot框架中最早执行的监听器,在该监听器执行started()方法时,会继续发布事件,也就是事件传递。这种实现主要还是基于spring的事件机制。
继续跟进SimpleApplicationEventMulticaster,有个核心方法:

  1. Override
  2. public void multicastEvent(final ApplicationEvent event, @Nullable ResolvableType eventType) {
  3. ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));
  4. for (final ApplicationListener<?> listener : getApplicationListeners(event, type)) {
  5. //获取线程池,如果为空则同步处理。这里线程池为空,还未没初始化。
  6. Executor executor = getTaskExecutor();
  7. if (executor != null) {
  8. //异步发送事件
  9. executor.execute(() -> invokeListener(listener, event));
  10. }
  11. else {
  12. //同步发送事件
  13. invokeListener(listener, event);
  14. }
  15. }
  16. }

这里会根据事件类型ApplicationStartingEvent获取对应的监听器,在容器启动之后执行响应的动作,有如下4种监听器:
image.png
这是springBoot启动过程中,第一处根据类型执行监听器的地方。根据发布的事件类型从上述10种监听器中选择对应的监听器进行事件发布,当然如果继承了 springCloud或者别的框架,就不止10个了。这里选了一个 springBoot 的日志监听器来进行讲解,核心代码如下:

  1. @Override
  2. public void onApplicationEvent(ApplicationEvent event) {
  3. //在springboot启动的时候
  4. if (event instanceof ApplicationStartedEvent) {
  5. onApplicationStartedEvent((ApplicationStartedEvent) event);
  6. }
  7. //springboot的Environment环境准备完成的时候
  8. else if (event instanceof ApplicationEnvironmentPreparedEvent) {
  9. onApplicationEnvironmentPreparedEvent(
  10. (ApplicationEnvironmentPreparedEvent) event);
  11. }
  12. //在springboot容器的环境设置完成以后
  13. else if (event instanceof ApplicationPreparedEvent) {
  14. onApplicationPreparedEvent((ApplicationPreparedEvent) event);
  15. }
  16. //容器关闭的时候
  17. else if (event instanceof ContextClosedEvent && ((ContextClosedEvent) event)
  18. .getApplicationContext().getParent() == null) {
  19. onContextClosedEvent();
  20. }
  21. //容器启动失败的时候
  22. else if (event instanceof ApplicationFailedEvent) {
  23. onApplicationFailedEvent();
  24. }
  25. }

因为我们的事件类型为ApplicationEvent,所以会执行onApplicationStartedEvent((ApplicationStartedEvent) event)。springBoot会在运行过程中的不同阶段,发送各种事件,来执行对应监听器的对应方法。大同小异,别的监听器执行流程这里不再赘述,后面会有单独的详解。

所有的监听器在运行的过程中需要监听某些事件,各种不同的监听器监听的事件是不一样的,在springapplication对象创建的时候创建了11个对象,但是这11个监听器的功能是不同的,换句话说就是监听的事件是不同的,当开始启动监听器的时候,要判断当前监听器是否能监听该事件,如果可以,正确启动;如果不可以,直接抛弃。

继续后面的流程。

3.2 构造环境

ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
继续跟进prepareEnvironment 方法,看一下构造环境的具体细节:

  1. private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners,
  2. ApplicationArguments applicationArguments) {
  3. //创建环境对象并返回StandardServletEnvironment
  4. ConfigurableEnvironment environment = getOrCreateEnvironment();
  5. //根据参数设置 PropertySources 和Profiles
  6. configureEnvironment(environment, applicationArguments.getSourceArgs());
  7. // propertySpurceList 添加configurationProperties
  8. ConfigurationPropertySources.attach(environment);
  9. //
  10. listeners.environmentPrepared(environment);
  11. bindToSpringApplication(environment);
  12. if (!this.isCustomEnvironment) {
  13. environment = new EnvironmentConverter(getClassLoader()).convertEnvironmentIfNecessary(environment,
  14. deduceEnvironmentClass());
  15. }
  16. ConfigurationPropertySources.attach(environment);
  17. return environment;

3.2.1 创建环境对象

来看一下getOrCreateEnvironment()方法,前面已经提到,environment已经被设置了servlet类型,所以这里创建的是环境对象是StandardServletEnvironment。

  1. private ConfigurableEnvironment getOrCreateEnvironment() {
  2. if (this.environment != null) {
  3. return this.environment;
  4. }
  5. switch (this.webApplicationType) {
  6. case SERVLET:
  7. return new StandardServletEnvironment();
  8. case REACTIVE:
  9. return new StandardReactiveWebEnvironment();
  10. default:
  11. return new StandardEnvironment();
  12. }
  13. }

在创建StandardServletEnvironment对象是发现类中并没有构造方法,所以跟踪一下类的继承关系如下:
image.png
即在创建对象的过程中会调用父类构造方法,然后加载环境配置数据。

  1. // 调用父类构造方法
  2. public AbstractEnvironment() {
  3. customizePropertySources(this.propertySources);
  4. }
  5. // 资源配置设置
  6. @Override
  7. protected void customizePropertySources(MutablePropertySources propertySources) {
  8. propertySources.addLast(new StubPropertySource(SERVLET_CONFIG_PROPERTY_SOURCE_NAME));
  9. propertySources.addLast(new StubPropertySource(SERVLET_CONTEXT_PROPERTY_SOURCE_NAME));
  10. if (JndiLocatorDelegate.isDefaultJndiEnvironmentAvailable()) {
  11. propertySources.addLast(new JndiPropertySource(JNDI_PROPERTY_SOURCE_NAME));
  12. }
  13. super.customizePropertySources(propertySources);
  14. }

创建完成StandardServletEnvironment对象创建完成后,返回ConfigurableEnvironment对象,对象中有几个重要属性值:activeProfiles, propertySpurceList,这个集合中主要包含和环境相关的四个对象。
image.png
执行到这里,系统变量和环境变量已经被载入到配置文件的集合中,接下来就行解析项目中的配置文件。

3.2.2 发布事件

来看一下listeners.environmentPrepared(environment);上面已经提到了,这里是第二次发布事件。什么事件?
顾名思义,系统环境初始化完成的事件。
发布事件的流程上面已经讲过了,这里不在赘述。来看一下根据事件类型获取到的监听器:
image.png
可以看到获取到的监听器和第一次发布启动事件获取的监听器有几个是重复的,这也验证了监听器是可以多次获取,根据事件类型来区分具体处理逻辑。上面介绍日志监听器的时候已经提到。
主要来看一下ConfigFileApplicationListener,该监听器非常核心,主要用来处理项目配置。项目中的 properties 和yml文件都是其内部类所加载。具体来看一下:
首先方法执行入口:

  1. protected void invokeListener(ApplicationListener<?> listener, ApplicationEvent event) {
  2. ErrorHandler errorHandler = getErrorHandler();
  3. if (errorHandler != null) {
  4. try {
  5. doInvokeListener(listener, event);
  6. }
  7. catch (Throwable err) {
  8. errorHandler.handleError(err);
  9. }
  10. }
  11. else {
  12. doInvokeListener(listener, event);
  13. }
  14. }
  15. //
  16. private void doInvokeListener(ApplicationListener listener, ApplicationEvent event) {
  17. try {
  18. listener.onApplicationEvent(event);
  19. }
  20. }

通过根据源码可以看到,所有的事件发布都会经过上面的几个方法过程

  1. this.initialMulticaster .multicastEvent():将给定的应用程序事件多播到适当的监听器。
  2. invokeListener(listener, event) : 使用给定的事件调用监听器
  3. doInvokeListener(listener, event) 第2步方法的真正执行操作者
    1. listener.onApplicationEvent(event): doInvokeListener()方法内部实现
  4. 调用所有监听器的父类ApplicationListener的onApplicationEvent()方法,根据读取得到的配置文件中的类进入到具体的实现类

在构造环境这个流程根据ConfigFileApplicationListener 这个监听器进行后面具体方法细节实现:

  1. private void onApplicationEnvironmentPreparedEvent(ApplicationEnvironmentPreparedEvent event) {
  2. List<EnvironmentPostProcessor> postProcessors = loadPostProcessors();
  3. postProcessors.add(this);
  4. AnnotationAwareOrderComparator.sort(postProcessors);
  5. for (EnvironmentPostProcessor postProcessor : postProcessors) {
  6. postProcessor.postProcessEnvironment(event.getEnvironment(), event.getSpringApplication());
  7. }
  8. }

�首先还是会去读spring.factories 文件,List postProcessors = loadPostProcessors();获取的处理类有以下四种:

  1. # Environment Post Processors
  2. org.springframework.boot.env.EnvironmentPostProcessor= //一个@FunctionalInterface函数式接口
  3. org.springframework.boot.cloud.CloudFoundryVcapEnvironmentPostProcessor//为springCloud提供的扩展类
  4. org.springframework.boot.env.SpringApplicationJsonEnvironmentPostProcessor//支持json环境变量
  5. org.springframework.boot.env.SystemEnvironmentPropertySourceEnvironmentPostProcessor //springBoo2提供的一个包装类,主要将`StandardServletEnvironment`包装成`SystemEnvironmentPropertySourceEnvironmentPostProcessor`对象

在执行完上述三个监听器流程后,ConfigFileApplicationListener会执行该类本身的逻辑。由其内部类Loader加载项目制定路径下的配置文件:

  1. private static final String DEFAULT_SEARCH_LOCATIONS = "classpath:/,classpath:/config/,file:./,file:./config/";

至此,项目的变量配置已全部加载完毕,来一起看一下:�
image.png
这里一共6个配置文件,取值顺序由上到下。也就是说前面的配置变量会覆盖后面同名的配置变量。项目配置变量的时候需要注意这点。

3.3 创建容器

  1. context = createApplicationContext();

接续跟进方法

  1. protected ConfigurableApplicationContext createApplicationContext() {
  2. Class<?> contextClass = this.applicationContextClass;
  3. if (contextClass == null) {
  4. try {
  5. switch (this.webApplicationType) {
  6. case SERVLET:
  7. contextClass = Class.forName(DEFAULT_SERVLET_WEB_CONTEXT_CLASS);
  8. break;
  9. case REACTIVE:
  10. contextClass = Class.forName(DEFAULT_REACTIVE_WEB_CONTEXT_CLASS);
  11. break;
  12. default:
  13. contextClass = Class.forName(DEFAULT_CONTEXT_CLASS);
  14. }
  15. }
  16. catch (ClassNotFoundException ex) {
  17. throw new IllegalStateException(
  18. "Unable create a default ApplicationContext, please specify an ApplicationContextClass", ex);
  19. }
  20. }
  21. return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);
  22. }

上面可以看出,这里创建容器的类型 还是根据webApplicationType进行判断的,上一篇已经讲述了该变量如何赋值的过程。因为该类型为SERVLET类型,所以会通过反射装载对应的字节码,如下:

  1. /**
  2. * The class name of application context that will be used by default for non-web
  3. * environments.
  4. */
  5. public static final String DEFAULT_CONTEXT_CLASS = "org.springframework.context."
  6. + "annotation.AnnotationConfigApplicationContext";
  7. /**
  8. * The class name of application context that will be used by default for web
  9. * environments.
  10. */
  11. public static final String DEFAULT_SERVLET_WEB_CONTEXT_CLASS = "org.springframework.boot."
  12. + "web.servlet.context.AnnotationConfigServletWebServerApplicationContext";
  13. /**
  14. * The class name of application context that will be used by default for reactive web
  15. * environments.
  16. */
  17. public static final String DEFAULT_REACTIVE_WEB_CONTEXT_CLASS = "org.springframework."
  18. + "boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext";

该对象是springBoot2创建的容器,后续所有的操作都会基于该容器。
image.png
AnnotationConfigServletWebServerApplicationContext.png

3.4 报告错误信息

  1. exceptionReporters = getSpringFactoriesInstances(
  2. SpringBootExceptionReporter.class,
  3. new Class[] { ConfigurableApplicationContext.class }, context);

这里还是以同样的方式获取 spring.factories文件中的指定类:

  1. exceptionReporters = getSpringFactoriesInstances(
  2. SpringBootExceptionReporter.class,
  3. new Class[] { ConfigurableApplicationContext.class }, context);

该类主要是在项目启动失败之后,打印log:

  1. private void reportFailure(Collection<SpringBootExceptionReporter> exceptionReporters,
  2. Throwable failure) {
  3. try {
  4. for (SpringBootExceptionReporter reporter : exceptionReporters) {
  5. if (reporter.reportException(failure)) {
  6. //上报错误log
  7. registerLoggedException(failure);
  8. return;
  9. }
  10. }
  11. }
  12. catch (Throwable ex) {
  13. // Continue with normal handling of the original failure
  14. }
  15. if (logger.isErrorEnabled()) {
  16. logger.error("Application run failed", failure);
  17. registerLoggedException(failure);
  18. }
  19. }

3.5 准备容器

这一步主要是在容器刷新之前的准备动作。包含一个非常关键的操作:将启动类注入容器,为后续开启自动化配置奠定基础。

  1. prepareContext(context, environment, listeners, applicationArguments, printedBanner);

继续跟进该方法

  1. private void prepareContext(ConfigurableApplicationContext context,
  2. ConfigurableEnvironment environment, SpringApplicationRunListeners listeners,
  3. ApplicationArguments applicationArguments, Banner printedBanner) {
  4. //设置容器环境,包括各种变量
  5. context.setEnvironment(environment);
  6. //执行容器后置处理
  7. postProcessApplicationContext(context);
  8. //执行容器中的ApplicationContextInitializer(包括 spring.factories和自定义的实例)
  9. applyInitializers(context);
  10. //发送容器已经准备好的事件,通知各监听器
  11. listeners.contextPrepared(context);
  12. //打印log
  13. if (this.logStartupInfo) {
  14. logStartupInfo(context.getParent() == null);
  15. logStartupProfileInfo(context);
  16. }
  17. // Add boot specific singleton beans
  18. //注册启动参数bean,这里将容器指定的参数封装成bean,注入容器
  19. context.getBeanFactory().registerSingleton("springApplicationArguments",
  20. applicationArguments);
  21. //设置banner
  22. if (printedBanner != null) {
  23. context.getBeanFactory().registerSingleton("springBootBanner", printedBanner);
  24. }
  25. // Load the sources
  26. //获取我们的启动类指定的参数,可以是多个
  27. Set<Object> sources = getAllSources();
  28. Assert.notEmpty(sources, "Sources must not be empty");
  29. //加载我们的启动类,将启动类注入容器
  30. load(context, sources.toArray(new Object[0]));
  31. //发布容器已加载事件。
  32. listeners.contextLoaded(context);
  33. }

来看一下上面的几个核心处理。
1)容器的后置处理:

  1. protected void postProcessApplicationContext(ConfigurableApplicationContext context) {
  2. if (this.beanNameGenerator != null) {
  3. context.getBeanFactory().registerSingleton(
  4. AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR,
  5. this.beanNameGenerator);
  6. }
  7. if (this.resourceLoader != null) {
  8. if (context instanceof GenericApplicationContext) {
  9. ((GenericApplicationContext) context)
  10. .setResourceLoader(this.resourceLoader);
  11. }
  12. if (context instanceof DefaultResourceLoader) {
  13. ((DefaultResourceLoader) context)
  14. .setClassLoader(this.resourceLoader.getClassLoader());
  15. }
  16. }
  17. }

这里默认不执行任何逻辑,因为beanNameGenerator和resourceLoader默认为空。之所以这样做,是springBoot留给我们的扩展处理方式,类似于这样的扩展,spring中也有很多。
2)加载启动指定类(重点)
这里会将我们的启动类加载spring容器beanDefinitionMap中,为后续springBoot 自动化配置奠定基础,springBoot为我们提供的各种注解配置也与此有关。

  1. load(context, sources.toArray(new Object[0]));
  1. protected void load(ApplicationContext context, Object[] sources) {
  2. if (logger.isDebugEnabled()) {
  3. logger.debug(
  4. "Loading source " + StringUtils.arrayToCommaDelimitedString(sources));
  5. }
  6. BeanDefinitionLoader loader = createBeanDefinitionLoader(
  7. getBeanDefinitionRegistry(context), sources);
  8. if (this.beanNameGenerator != null) {
  9. loader.setBeanNameGenerator(this.beanNameGenerator);
  10. }
  11. if (this.resourceLoader != null) {
  12. loader.setResourceLoader(this.resourceLoader);
  13. }
  14. if (this.environment != null) {
  15. loader.setEnvironment(this.environment);
  16. }
  17. loader.load();
  18. }

这里参数即为我们项目启动时传递的参数:SpringApplication.run(SpringBootApplication.class, args);由于我们指定了启动类,所以上面也就是加载启动类到容器。**

  1. private int load(Class<?> source) {
  2. if (isGroovyPresent()
  3. && GroovyBeanDefinitionSource.class.isAssignableFrom(source)) {
  4. // Any GroovyLoaders added in beans{} DSL can contribute beans here
  5. GroovyBeanDefinitionSource loader = BeanUtils.instantiateClass(source,
  6. GroovyBeanDefinitionSource.class);
  7. load(loader);
  8. }
  9. if (isComponent(source)) {
  10. //以注解的方式,将启动类bean信息存入beanDefinitionMap
  11. this.annotatedReader.register(source);
  12. return 1;
  13. }
  14. return 0;
  15. }

上面代码中启动类被加载到 beanDefinitionMap中,后续该启动类将作为开启自动化配置的入口,后面一篇文章我会详细的分析,启动类是如何加载,以及自动化配置开启的详细流程。

3)通知监听器,容器已准备就绪

  1. listeners.contextLoaded(context);

3.6 刷新容器

  1. refreshContext(context);
  1. protected void refresh(ApplicationContext applicationContext) {
  2. Assert.isInstanceOf(AbstractApplicationContext.class, applicationContext);
  3. ((AbstractApplicationContext) applicationContext).refresh();
  4. }

执行到这里,springBoot相关的处理工作已经结束,接下的工作就交给了spring。详细代码就不贴了

3.7 刷新容器后的扩展接口

  1. protected void afterRefresh(ConfigurableApplicationContext context,
  2. ApplicationArguments args) {
  3. }

扩展接口,设计模式中的模板方法,默认为空实现。如果有自定义需求,可以重写该方法。比如打印一些启动结束log,或者一些其它后置处理。

二、启动流程图

SpringBoot启动流程.png

二、SpringBoot 自动装配

1、SpringBoot 注解

SpringBoot 整个项目通过一个主类作为整个程序的入口,在这个主类中有个核心的注解:@SpringBootApplication,所有的装配和Bean 初始化都是通过注解进行解析扫描完成的。注解直接关系如下

  1. ![SpringBoot 注解继承关系.png](https://cdn.nlark.com/yuque/0/2022/png/12747730/1652844604689-214595d6-ba78-4e9b-8168-d05f03ac2a23.png#clientId=u03de5f67-cf5c-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=343&id=ud15d0a71&margin=%5Bobject%20Object%5D&name=SpringBoot%20%E6%B3%A8%E8%A7%A3%E7%BB%A7%E6%89%BF%E5%85%B3%E7%B3%BB.png&originHeight=685&originWidth=984&originalType=binary&ratio=1&rotation=0&showTitle=false&size=111722&status=done&style=none&taskId=u71e95d89-eb91-47d0-a08e-3c55839a2d5&title=&width=492)

�2、SpringBoot 自动装配流程

1.前置

SpringBoot 最核心的就是自动化配置,整个自动化配置主要包括以下几个核心点:

  1. spring.factories 配置文件中EnableAutoConfiguration提前配置的配置类
  2. 入口为启动流程中的 prepareContext()方法中的 load()方法加载主类到Spring容器中进行初始化
  3. 核心实现逻辑在Spring.refresh()14 个方法中的 invokeBeanFactoryPostProcessor中
  4. 核心类:AutoConfigurationImportSelector,通过方法调用返回整个项目使用的启动配置类

1.spring.factories 文件的具体类容:@EnableAutoConfiguration
image.png

  1. # Initializers
  2. org.springframework.context.ApplicationContextInitializer=\
  3. org.springframework.boot.autoconfigure.SharedMetadataReaderFactoryContextInitializer,\
  4. org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener
  5. # Application Listeners
  6. org.springframework.context.ApplicationListener=\
  7. org.springframework.boot.autoconfigure.BackgroundPreinitializer
  8. # Environment Post Processors
  9. org.springframework.boot.env.EnvironmentPostProcessor=\
  10. org.springframework.boot.autoconfigure.integration.IntegrationPropertiesEnvironmentPostProcessor
  11. # Auto Configuration Import Listeners
  12. org.springframework.boot.autoconfigure.AutoConfigurationImportListener=\
  13. org.springframework.boot.autoconfigure.condition.ConditionEvaluationReportAutoConfigurationImportListener
  14. # Auto Configuration Import Filters
  15. org.springframework.boot.autoconfigure.AutoConfigurationImportFilter=\
  16. org.springframework.boot.autoconfigure.condition.OnBeanCondition,\
  17. org.springframework.boot.autoconfigure.condition.OnClassCondition,\
  18. org.springframework.boot.autoconfigure.condition.OnWebApplicationCondition
  19. # Auto Configure
  20. org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  21. org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
  22. org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
  23. org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
  24. org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\
  25. org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\
  26. org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\
  27. org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,\
  28. org.springframework.boot.autoconfigure.context.LifecycleAutoConfiguration,\
  29. org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration,\
  30. org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration,\
  31. org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration,\
  32. org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration,\
  33. org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration,\
  34. org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveDataAutoConfiguration,\
  35. org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveRepositoriesAutoConfiguration,\
  36. org.springframework.boot.autoconfigure.data.cassandra.CassandraRepositoriesAutoConfiguration,\
  37. org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration,\
  38. org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveDataAutoConfiguration,\
  39. org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveRepositoriesAutoConfiguration,\
  40. org.springframework.boot.autoconfigure.data.couchbase.CouchbaseRepositoriesAutoConfiguration,\
  41. org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration,\
  42. org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration,\
  43. org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRepositoriesAutoConfiguration,\
  44. org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRestClientAutoConfiguration,\
  45. org.springframework.boot.autoconfigure.data.jdbc.JdbcRepositoriesAutoConfiguration,\
  46. org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration,\
  47. org.springframework.boot.autoconfigure.data.ldap.LdapRepositoriesAutoConfiguration,\
  48. org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,\
  49. org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration,\
  50. org.springframework.boot.autoconfigure.data.mongo.MongoReactiveRepositoriesAutoConfiguration,\
  51. org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration,\
  52. org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration,\
  53. org.springframework.boot.autoconfigure.data.neo4j.Neo4jReactiveDataAutoConfiguration,\
  54. org.springframework.boot.autoconfigure.data.neo4j.Neo4jReactiveRepositoriesAutoConfiguration,\
  55. org.springframework.boot.autoconfigure.data.neo4j.Neo4jRepositoriesAutoConfiguration,\
  56. org.springframework.boot.autoconfigure.data.r2dbc.R2dbcDataAutoConfiguration,\
  57. org.springframework.boot.autoconfigure.data.r2dbc.R2dbcRepositoriesAutoConfiguration,\
  58. org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,\
  59. org.springframework.boot.autoconfigure.data.redis.RedisReactiveAutoConfiguration,\
  60. org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration,\
  61. org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration,\
  62. org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration,\
  63. org.springframework.boot.autoconfigure.elasticsearch.ElasticsearchRestClientAutoConfiguration,\
  64. org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\
  65. org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,\
  66. org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration,\
  67. org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration,\
  68. org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration,\
  69. org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration,\
  70. org.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfiguration,\
  71. org.springframework.boot.autoconfigure.hazelcast.HazelcastJpaDependencyAutoConfiguration,\
  72. org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration,\
  73. org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration,\
  74. org.springframework.boot.autoconfigure.influx.InfluxDbAutoConfiguration,\
  75. org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration,\
  76. org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration,\
  77. org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration,\
  78. org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
  79. org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration,\
  80. org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration,\
  81. org.springframework.boot.autoconfigure.jdbc.XADataSourceAutoConfiguration,\
  82. org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration,\
  83. org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration,\
  84. org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration,\
  85. org.springframework.boot.autoconfigure.jms.JndiConnectionFactoryAutoConfiguration,\
  86. org.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfiguration,\
  87. org.springframework.boot.autoconfigure.jms.artemis.ArtemisAutoConfiguration,\
  88. org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration,\
  89. org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration,\
  90. org.springframework.boot.autoconfigure.jsonb.JsonbAutoConfiguration,\
  91. org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration,\
  92. org.springframework.boot.autoconfigure.availability.ApplicationAvailabilityAutoConfiguration,\
  93. org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration,\
  94. org.springframework.boot.autoconfigure.ldap.LdapAutoConfiguration,\
  95. org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration,\
  96. org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration,\
  97. org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration,\
  98. org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration,\
  99. org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,\
  100. org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration,\
  101. org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration,\
  102. org.springframework.boot.autoconfigure.neo4j.Neo4jAutoConfiguration,\
  103. org.springframework.boot.autoconfigure.netty.NettyAutoConfiguration,\
  104. org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\
  105. org.springframework.boot.autoconfigure.quartz.QuartzAutoConfiguration,\
  106. org.springframework.boot.autoconfigure.r2dbc.R2dbcAutoConfiguration,\
  107. org.springframework.boot.autoconfigure.r2dbc.R2dbcTransactionManagerAutoConfiguration,\
  108. org.springframework.boot.autoconfigure.rsocket.RSocketMessagingAutoConfiguration,\
  109. org.springframework.boot.autoconfigure.rsocket.RSocketRequesterAutoConfiguration,\
  110. org.springframework.boot.autoconfigure.rsocket.RSocketServerAutoConfiguration,\
  111. org.springframework.boot.autoconfigure.rsocket.RSocketStrategiesAutoConfiguration,\
  112. org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration,\
  113. org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration,\
  114. org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration,\
  115. org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration,\
  116. org.springframework.boot.autoconfigure.security.reactive.ReactiveUserDetailsServiceAutoConfiguration,\
  117. org.springframework.boot.autoconfigure.security.rsocket.RSocketSecurityAutoConfiguration,\
  118. org.springframework.boot.autoconfigure.security.saml2.Saml2RelyingPartyAutoConfiguration,\
  119. org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration,\
  120. org.springframework.boot.autoconfigure.session.SessionAutoConfiguration,\
  121. org.springframework.boot.autoconfigure.security.oauth2.client.servlet.OAuth2ClientAutoConfiguration,\
  122. org.springframework.boot.autoconfigure.security.oauth2.client.reactive.ReactiveOAuth2ClientAutoConfiguration,\
  123. org.springframework.boot.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerAutoConfiguration,\
  124. org.springframework.boot.autoconfigure.security.oauth2.resource.reactive.ReactiveOAuth2ResourceServerAutoConfiguration,\
  125. org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration,\
  126. org.springframework.boot.autoconfigure.sql.init.SqlInitializationAutoConfiguration,\
  127. org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration,\
  128. org.springframework.boot.autoconfigure.task.TaskSchedulingAutoConfiguration,\
  129. org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration,\
  130. org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration,\
  131. org.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfiguration,\
  132. org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration,\
  133. org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration,\
  134. org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration,\
  135. org.springframework.boot.autoconfigure.web.reactive.HttpHandlerAutoConfiguration,\
  136. org.springframework.boot.autoconfigure.web.reactive.ReactiveMultipartAutoConfiguration,\
  137. org.springframework.boot.autoconfigure.web.reactive.ReactiveWebServerFactoryAutoConfiguration,\
  138. org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration,\
  139. org.springframework.boot.autoconfigure.web.reactive.WebSessionIdResolverAutoConfiguration,\
  140. org.springframework.boot.autoconfigure.web.reactive.error.ErrorWebFluxAutoConfiguration,\
  141. org.springframework.boot.autoconfigure.web.reactive.function.client.ClientHttpConnectorAutoConfiguration,\
  142. org.springframework.boot.autoconfigure.web.reactive.function.client.WebClientAutoConfiguration,\
  143. org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,\
  144. org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration,\
  145. org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration,\
  146. org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration,\
  147. org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration,\
  148. org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,\
  149. org.springframework.boot.autoconfigure.websocket.reactive.WebSocketReactiveAutoConfiguration,\
  150. org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration,\
  151. org.springframework.boot.autoconfigure.websocket.servlet.WebSocketMessagingAutoConfiguration,\
  152. org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration,\
  153. org.springframework.boot.autoconfigure.webservices.client.WebServiceTemplateAutoConfiguration
  154. # Failure analyzers
  155. org.springframework.boot.diagnostics.FailureAnalyzer=\
  156. org.springframework.boot.autoconfigure.data.redis.RedisUrlSyntaxFailureAnalyzer,\
  157. org.springframework.boot.autoconfigure.diagnostics.analyzer.NoSuchBeanDefinitionFailureAnalyzer,\
  158. org.springframework.boot.autoconfigure.flyway.FlywayMigrationScriptMissingFailureAnalyzer,\
  159. org.springframework.boot.autoconfigure.jdbc.DataSourceBeanCreationFailureAnalyzer,\
  160. org.springframework.boot.autoconfigure.jdbc.HikariDriverConfigurationFailureAnalyzer,\
  161. org.springframework.boot.autoconfigure.jooq.NoDslContextBeanFailureAnalyzer,\
  162. org.springframework.boot.autoconfigure.r2dbc.ConnectionFactoryBeanCreationFailureAnalyzer,\
  163. org.springframework.boot.autoconfigure.r2dbc.MissingR2dbcPoolDependencyFailureAnalyzer,\
  164. org.springframework.boot.autoconfigure.r2dbc.MultipleConnectionPoolConfigurationsFailureAnalzyer,\
  165. org.springframework.boot.autoconfigure.r2dbc.NoConnectionFactoryBeanFailureAnalyzer,\
  166. org.springframework.boot.autoconfigure.session.NonUniqueSessionRepositoryFailureAnalyzer
  167. # Template availability providers
  168. org.springframework.boot.autoconfigure.template.TemplateAvailabilityProvider=\
  169. org.springframework.boot.autoconfigure.freemarker.FreeMarkerTemplateAvailabilityProvider,\
  170. org.springframework.boot.autoconfigure.mustache.MustacheTemplateAvailabilityProvider,\
  171. org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAvailabilityProvider,\
  172. org.springframework.boot.autoconfigure.thymeleaf.ThymeleafTemplateAvailabilityProvider,\
  173. org.springframework.boot.autoconfigure.web.servlet.JspTemplateAvailabilityProvider
  174. # DataSource initializer detectors
  175. org.springframework.boot.sql.init.dependency.DatabaseInitializerDetector=\
  176. org.springframework.boot.autoconfigure.flyway.FlywayMigrationInitializerDatabaseInitializerDetector
  177. # Depends on database initialization detectors
  178. org.springframework.boot.sql.init.dependency.DependsOnDatabaseInitializationDetector=\
  179. org.springframework.boot.autoconfigure.batch.JobRepositoryDependsOnDatabaseInitializationDetector,\
  180. org.springframework.boot.autoconfigure.quartz.SchedulerDependsOnDatabaseInitializationDetector,\
  181. org.springframework.boot.autoconfigure.session.JdbcIndexedSessionRepositoryDependsOnDatabaseInitializationDetector

SPI 机制了解:
https://blog.csdn.net/qq_43522770/article/details/117284372

2.自动装配流程

  1. 整体自动准配都是从SpringBootApplicatio注解开始的,所以后面的解释主要从这个注解展开

1)springBoot启动类加载

首先加载启动类到Spring bean容器中的map中,这一步操作是在SpringBoot启动流程中prepareContext()方法中的load(context, sources.toArray(new Object[0]))方法完成。

  1. springboot 程序入口

    1. @SpringBootApplication
    2. public class DavinciServerApplication {
    3. public static void main(String[] args) {
    4. SpringApplication.run(DavinciServerApplication.class, args);
    5. }
    6. }
  2. springboot 启动流程 run() 方法,中间代码省去,只留使用到的核心方法

    1. public ConfigurableApplicationContext run(String... args) {
    2. .......
    3. // 加载SpringBoot 启动类到Spring容器中的入口类
    4. prepareContext(context, environment, listeners, applicationArguments, printedBanner);
    5. // 调用Spring底层实现,真正自动装配的逻辑在这里的一个底层方法中
    6. refreshContext(context);
    7. .......
    8. return context;
    9. }
  3. 加载启动类,核心方法BeanDefinitionLoader.load(Class<?> source)

    1. 跟进代码,最后会执行到**BeanDefinitionLoader.load(Class<?> source)方法中**

    ```java private int load(Object source) {

    1. Assert.notNull(source, "Source must not be null");
    2. //如果是class类型,启用注解类型
    3. if (source instanceof Class<?>) {
    4. return load((Class<?>) source);
    5. }
    6. //如果是resource类型,启用xml解析
    7. if (source instanceof Resource) {
    8. return load((Resource) source);
    9. }
    10. //如果是package类型,启用扫描包,例如:@ComponentScan
    11. if (source instanceof Package) {
    12. return load((Package) source);
    13. }
    14. //如果是字符串类型,直接加载
    15. if (source instanceof CharSequence) {
    16. return load((CharSequence) source);
    17. }
    18. throw new IllegalArgumentException("Invalid source type " + source.getClass());

    }

  1. 继续跟进load(Class<?> resource)方法<br /> ![image.png](https://cdn.nlark.com/yuque/0/2022/png/12747730/1652846594757-b32ae518-cc26-4a9b-868b-f04348309a9e.png#clientId=u03de5f67-cf5c-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=265&id=u34c6e72b&margin=%5Bobject%20Object%5D&name=image.png&originHeight=530&originWidth=1442&originalType=binary&ratio=1&rotation=0&showTitle=false&size=101220&status=done&style=none&taskId=ucfb5e76a-f57c-42eb-9987-6efcc556636&title=&width=721)<br />上述方法判断启动类中是否包含@component注解,可我们的启动类并没有该注解。继续跟进会发现,AnnotationUtils判断是否包含该注解是通过递归实现,注解上的注解若包含指定类型也是可以的。<br />启动类中包含@SpringBootApplication注解,进一步查找到@SpringBootConfiguration注解,然后查找到@Component注解,注解对应关系见[SpringBoot 注解](SpringBoot 注解)。
  2. 4. ** 注册bean定义详细到BeanDefinitionMap中为后期初始化bean做准备。**
  3. 跟进上图截取的代码 annotatedReader.register(source)方法, 最后执行到**AnnotateBeanDefinitionReader.register(source)方法中**
  4. ```java
  5. private <T> void doRegisterBean(Class<T> beanClass, @Nullable String name,
  6. @Nullable Class<? extends Annotation>[] qualifiers, @Nullable Supplier<T> supplier,
  7. @Nullable BeanDefinitionCustomizer[] customizers) {
  8. AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(beanClass);
  9. BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
  10. definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
  11. BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
  12. }

如此一来,我们的启动类就被包装成AnnotatedGenericBeanDefinition了,后续启动类的处理都基于该对象。
到此也完成了prepareContext()方法,进入到SpringBoot启动流程中的refreshContext()方法。

2)自动装配入口

从启动流程开始,到Spring的刷新容器为真正的入口。refreshContext() 中层层调用refresh()方法进入到最后执行到Spring.refresh()方法

  1. @Override
  2. public void refresh() throws BeansException, IllegalStateException {
  3. synchronized (this.startupShutdownMonitor) {
  4. // ...
  5. invokeBeanFactoryPostProcessors(beanFactory);
  6. // ...
  7. }

继续跟进 invokeBeanFactoryPostProcessors()方法:

  1. protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
  2. //开始执行beanFactoryPostProcessor对应实现类
  3. PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
  4. // Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
  5. // (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
  6. if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
  7. beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
  8. beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
  9. }
  10. }

首先我们要知道beanFactoryPostProcessor接口是spring的扩展接口,从名字也可以看出,是 beanFactory的扩展接口。在刷新容器之前,该接口可用来修改bean元数据信息。具体实现方式,我们继续跟着上述执行逻辑便知。
继续跟进上面invokeBeanFactoryPostProcessors方法,第一行很关键:

  1. //开始执行beanFactoryPostProcessor对应实现类
  2. PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());

一个比较核心的代理类出现了,AbstractApplicationContext委托执行postprocessors任务的工具类。
而在项目启动时会委托什么任务呢?
在Spring 源码中:SpringApplication类中applyInitializers(context)方法,它会将三个默认的内部类加入到 spring 容器DefaultListableBeanFactory中,如下:

  1. //设置配置警告
  2. ConfigurationWarningsApplicationContextInitializer$ConfigurationWarningsPostProcessor
  3. SharedMetadataReaderFactoryContextInitializer$CachingMetadataReaderFactoryPostProcessor
  4. ConfigFileApplicationListener$PropertySourceOrderingPostProcessor

来看一下具体任务执行细节,跟进invokeBeanFactoryPostProcessors方法:

  1. public static void invokeBeanFactoryPostProcessors(
  2. ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
  3. // Invoke BeanDefinitionRegistryPostProcessors first, if any.
  4. Set<String> processedBeans = new HashSet<>();
  5. if (beanFactory instanceof BeanDefinitionRegistry) {
  6. // 将beanFactory 强转为BeanDefinitionRegisrty 对象
  7. BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
  8. // 创建两个空的对象来设置需要处理的 后置处理器
  9. List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
  10. List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
  11. // 将两种类型区分分别添加到创建的空集合中分别处理
  12. for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
  13. if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
  14. BeanDefinitionRegistryPostProcessor registryProcessor =
  15. (BeanDefinitionRegistryPostProcessor) postProcessor;
  16. registryProcessor.postProcessBeanDefinitionRegistry(registry);
  17. registryProcessors.add(registryProcessor);
  18. }
  19. else {
  20. regularPostProcessors.add(postProcessor);
  21. }
  22. }
  23. // Do not initialize FactoryBeans here: We need to leave all regular beans
  24. // uninitialized to let the bean factory post-processors apply to them!
  25. // Separate between BeanDefinitionRegistryPostProcessors that implement
  26. // PriorityOrdered, Ordered, and the rest.
  27. List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
  28. // First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
  29. // 调用所有实现PriorityOrdered接口的BeanDefinitionRegistryPostProcessor实现类
  30. // 找到所有实现BeanDefinitionRegistryPostProcessor接口bean的beanName
  31. String[] postProcessorNames =
  32. beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
  33. for (String ppName : postProcessorNames) {
  34. // 检测是否实现来PriorityOrdered 接口
  35. if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
  36. currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
  37. processedBeans.add(ppName);
  38. }
  39. }
  40. // 按照优先级进行排序操作
  41. sortPostProcessors(currentRegistryProcessors, beanFactory);
  42. // 添加到 registryProcessors 中,用于最后执行postProcessBeanFactory 方法
  43. registryProcessors.addAll(currentRegistryProcessors);
  44. invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
  45. currentRegistryProcessors.clear();
  46. // Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
  47. postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
  48. for (String ppName : postProcessorNames) {
  49. if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
  50. currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
  51. processedBeans.add(ppName);
  52. }
  53. }
  54. sortPostProcessors(currentRegistryProcessors, beanFactory);
  55. registryProcessors.addAll(currentRegistryProcessors);
  56. invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
  57. currentRegistryProcessors.clear();
  58. // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
  59. boolean reiterate = true;
  60. while (reiterate) {
  61. reiterate = false;
  62. postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
  63. for (String ppName : postProcessorNames) {
  64. if (!processedBeans.contains(ppName)) {
  65. currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
  66. processedBeans.add(ppName);
  67. reiterate = true;
  68. }
  69. }
  70. sortPostProcessors(currentRegistryProcessors, beanFactory);
  71. registryProcessors.addAll(currentRegistryProcessors);
  72. invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
  73. currentRegistryProcessors.clear();
  74. }
  75. // Now, invoke the postProcessBeanFactory callback of all processors handled so far.
  76. invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
  77. invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
  78. }
  79. else {
  80. // Invoke factory processors registered with the context instance.
  81. invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
  82. }
  83. // Do not initialize FactoryBeans here: We need to leave all regular beans
  84. // uninitialized to let the bean factory post-processors apply to them!
  85. String[] postProcessorNames =
  86. beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
  87. // Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
  88. // Ordered, and the rest.
  89. // 定义了存放实现了PriorityOrdered 接口的BeanPostProcessor集合
  90. List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
  91. // 定了存放实现了Ordered接口的BeanPostProcessor的name 集合
  92. List<String> orderedPostProcessorNames = new ArrayList<>();
  93. // 定义存放着普通的BeanPostProcessor的name集合
  94. List<String> nonOrderedPostProcessorNames = new ArrayList<>();
  95. for (String ppName : postProcessorNames) {
  96. if (processedBeans.contains(ppName)) {
  97. // skip - already processed in first phase above
  98. }
  99. else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
  100. priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
  101. }
  102. else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
  103. orderedPostProcessorNames.add(ppName);
  104. }
  105. else {
  106. nonOrderedPostProcessorNames.add(ppName);
  107. }
  108. }
  109. // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
  110. sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
  111. invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
  112. // Next, invoke the BeanFactoryPostProcessors that implement Ordered.
  113. List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>();
  114. for (String postProcessorName : orderedPostProcessorNames) {
  115. orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
  116. }
  117. sortPostProcessors(orderedPostProcessors, beanFactory);
  118. invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
  119. // Finally, invoke all other BeanFactoryPostProcessors.
  120. List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
  121. for (String postProcessorName : nonOrderedPostProcessorNames) {
  122. nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
  123. }
  124. invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
  125. // Clear cached merged bean definitions since the post-processors might have
  126. // modified the original metadata, e.g. replacing placeholders in values...
  127. beanFactory.clearMetadataCache();
  128. }

来分析一下核心代码:

  1. String[] postProcessorNames =
  2. beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);

这行代码通过类型BeanDefinitionRegistryPostProcessor获取的处理类名称为:
“org.springframework.context.annotation.internalConfigurationAnnotationProcessor”
而在源码中却搜不到internalConfigurationAnnotationProcessor类,为什么呢?当启动springBoot,创建springBoot容器上下文AnnotationConfigServletWebApplicationContext时,会装配几个默认bean:

  1. public AnnotationConfigServletWebApplicationContext() {
  2. //在这里装配
  3. this.reader = new AnnotatedBeanDefinitionReader(this);
  4. this.scanner = new ClassPathBeanDefinitionScanner(this);
  5. }

在执行创建springBoot 上下文:context = createApplicationContext() 对象时生成ConfigurableApplicationContext对象,�然后同时创建AnnotatedBeanDefinitionReader对象,然后调用其构造方法,进行ConfigurationClassPostProcessor设置

  1. public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {
  2. //...
  3. AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
  4. }

继续跟进会执行registerAnnotationConfigProcessors方法:

  1. public static final String CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME =
  2. "org.springframework.context.annotation.internalConfigurationAnnotationProcessor";
  3. //将 internalConfigurationAnnotationProcessor 对应的类包装成 RootBeanDefinition 加载到容器
  4. if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
  5. RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
  6. def.setSource(source);
  7. beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
  8. }

到这里,答案清晰浮现。internalConfigurationAnnotationProcessor为bean名称,容器中真正的类则是ConfigurationClassPostProcessor
继续后面流程,获取ConfigurationClassPostProcessor后,开始执行BeanDefinitionRegistryPostProcessor:

  1. //开始执行装配逻辑
  2. invokeBeanDefinitionRegistryPostProcessors(priorityOrderedPostProcessors, registry);

3)开始执行自动配置逻辑(启动类指定的配置,非默认配置):

首先开始通过一个方法的多个类中调用过程,最后一步到解析过程

  1. #PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors()
  2. #PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors()
  3. #BeanDefinitionRegistryPostProcessor.postProcessBeanDefinitionRegistry
  4. BeanDefinitionRegistryPostProcessor是抽象类,具体实现有子类来实现,SpringBoot中的实现类为
  5. ConfigurationClassPostProcessor
  6. #ConfigurationClassPostProcessor.processConfigBeanDefinitions()

继续跟进processConfigBeanDefinitions()方法细节:
image.png
首先获得ConfigurationClassParser,这个是所有配置类的解析类,比较核心。所有的解析逻辑在parser.parse(candidates);中,我们详细的来看一下:

  1. public void parse(Set<BeanDefinitionHolder> configCandidates) {
  2. this.deferredImportSelectors = new LinkedList<DeferredImportSelectorHolder>();
  3. for (BeanDefinitionHolder holder : configCandidates) {
  4. BeanDefinition bd = holder.getBeanDefinition();
  5. try {
  6. //是否是注解类
  7. if (bd instanceof AnnotatedBeanDefinition) {
  8. parse(((AnnotatedBeanDefinition) bd).getMetadata(), holder.getBeanName());
  9. }
  10. else if (bd instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) bd).hasBeanClass()) {
  11. parse(((AbstractBeanDefinition) bd).getBeanClass(), holder.getBeanName());
  12. }
  13. else {
  14. parse(bd.getBeanClassName(), holder.getBeanName());
  15. }
  16. }
  17. catch (BeanDefinitionStoreException ex) {
  18. throw ex;
  19. }
  20. catch (Exception ex) {
  21. throw new BeanDefinitionStoreException(
  22. "Failed to parse configuration class [" + bd.getBeanClassName() + "]", ex);
  23. }
  24. }
  25. //执行配置类
  26. processDeferredImportSelectors();
  27. }

继续跟进parse方法:

  1. protected void processConfigurationClass(ConfigurationClass configClass) throws IOException {
  2. //...省略不核心代码
  3. // Recursively process the configuration class and its superclass hierarchy.
  4. SourceClass sourceClass = asSourceClass(configClass);
  5. do {
  6. //循环处理bean,如果有父类,则处理父类。直至结束。
  7. sourceClass = doProcessConfigurationClass(configClass, sourceClass);
  8. }
  9. while (sourceClass != null);
  10. this.configurationClasses.put(configClass, configClass);
  11. }

继续跟进doProcessConfigurationClass方法,该方法可以说是 spring 框架支持注解配置的核心逻辑了:

  1. protected final SourceClass doProcessConfigurationClass(ConfigurationClass configClass, SourceClass sourceClass) throws IOException {
  2. //处理内部类逻辑,由于传来的参数是我们的启动类,不含内部类,所以跳过。
  3. processMemberClasses(configClass, sourceClass);
  4. // Process any @PropertySource annotations
  5. //针对属性配置的解析
  6. for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(
  7. sourceClass.getMetadata(), PropertySources.class, org.springframework.context.annotation.PropertySource.class)) {
  8. if (this.environment instanceof ConfigurableEnvironment) {
  9. processPropertySource(propertySource);
  10. }
  11. else {
  12. logger.warn("Ignoring @PropertySource annotation on [" + sourceClass.getMetadata().getClassName() +
  13. "]. Reason: Environment must implement ConfigurableEnvironment");
  14. }
  15. }
  16. //这里是根据启动类 @ComponentScan 注解来扫描项目中的bean
  17. AnnotationAttributes componentScan = AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ComponentScan.class);
  18. if (componentScan != null && !this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {
  19. // The config class is annotated with @ComponentScan -> perform the scan immediately
  20. Set<BeanDefinitionHolder> scannedBeanDefinitions =
  21. this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());
  22. // Check the set of scanned definitions for any further config classes and parse recursively if necessary
  23. //遍历我们项目中的bean,如果是注解定义的bean,则进一步解析
  24. for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
  25. //判断是否是注解bean
  26. if (ConfigurationClassUtils.checkConfigurationClassCandidate(holder.getBeanDefinition(), this.metadataReaderFactory)) {
  27. //这里是关键,递归解析。所有的bean,如果有注解,会进一步解析注解中包含的bean
  28. parse(holder.getBeanDefinition().getBeanClassName(), holder.getBeanName());
  29. }
  30. }
  31. }
  32. // Process any @Import annotations
  33. //这里又是一个递归解析,获取导入的配置类。很多情况下,导入的配置类中会同样包含导入类注解。
  34. processImports(configClass, sourceClass, getImports(sourceClass), true);
  35. // Process any @ImportResource annotations
  36. //解析导入的 xml 配置类
  37. if (sourceClass.getMetadata().isAnnotated(ImportResource.class.getName())) {
  38. AnnotationAttributes importResource = AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);
  39. String[] resources = importResource.getAliasedStringArray("locations", ImportResource.class, sourceClass);
  40. Class<? extends BeanDefinitionReader> readerClass = importResource.getClass("reader");
  41. for (String resource : resources) {
  42. String resolvedResource = this.environment.resolveRequiredPlaceholders(resource);
  43. configClass.addImportedResource(resolvedResource, readerClass);
  44. }
  45. }
  46. // Process individual @Bean methods
  47. Set<MethodMetadata> beanMethods = sourceClass.getMetadata().getAnnotatedMethods(Bean.class.getName());
  48. for (MethodMetadata methodMetadata : beanMethods) {
  49. configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
  50. }
  51. // 获取接口中的默认方法,1.8以上的处理逻辑
  52. for (SourceClass ifc : sourceClass.getInterfaces()) {
  53. beanMethods = ifc.getMetadata().getAnnotatedMethods(Bean.class.getName());
  54. for (MethodMetadata methodMetadata : beanMethods) {
  55. if (!methodMetadata.isAbstract()) {
  56. // A default method or other concrete method on a Java 8+ interface...
  57. configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
  58. }
  59. }
  60. }
  61. // Process superclass, if any
  62. //如果该类有父类,则继续返回。上层方法判断不为空,则继续递归执行。
  63. if (sourceClass.getMetadata().hasSuperClass()) {
  64. String superclass = sourceClass.getMetadata().getSuperClassName();
  65. if (!superclass.startsWith("java") && !this.knownSuperclasses.containsKey(superclass)) {
  66. this.knownSuperclasses.put(superclass, configClass);
  67. // Superclass found, return its annotation metadata and recurse
  68. return sourceClass.getSuperClass();
  69. }
  70. }
  71. // No superclass -> processing is complete
  72. //递归实现,superclass为空,则结束递归中的循环
  73. return null;
  74. }

来看一下获取导入配置类的逻辑:

  1. processImports(configClass, sourceClass, getImports(sourceClass), true);

自定义配置都在 getImports() 中执行。。。。

4)开始执行 SpringBoot 默认配置逻辑

继续回到ConfigurationClassParser中的parse方法,回到该方法的最后一步:

  1. public void parse(Set<BeanDefinitionHolder> configCandidates) {
  2. // ...
  3. this.deferredImportSelectorHandler.process();
  4. }
  5. //deferredImportSelectorHandler 是定义在ConfigurationClassParser 类中的一个内部类
  6. private final DeferredImportSelectorHandler deferredImportSelectorHandler = new DeferredImportSelectorHandler();

继续跟进process()方法:

  1. public void process() {
  2. List<DeferredImportSelectorHolder> deferredImports = this.deferredImportSelectors;
  3. this.deferredImportSelectors = null;
  4. try {
  5. if (deferredImports != null) {
  6. DeferredImportSelectorGroupingHandler handler = new DeferredImportSelectorGroupingHandler();
  7. deferredImports.sort(DEFERRED_IMPORT_COMPARATOR);
  8. deferredImports.forEach(handler::register);
  9. handler.processGroupImports();
  10. }
  11. }
  12. finally {
  13. this.deferredImportSelectors = new ArrayList<>();
  14. }
  15. }
  16. }
  17. //
  18. public void processGroupImports() {
  19. for (DeferredImportSelectorGrouping grouping : this.groupings.values()) {
  20. grouping.getImports().forEach(entry -> {
  21. ConfigurationClass configurationClass = this.configurationClasses.get(
  22. entry.getMetadata());
  23. try {
  24. processImports(configurationClass, asSourceClass(configurationClass),
  25. asSourceClasses(entry.getImportClassName()), false);
  26. }
  27. catch (BeanDefinitionStoreException ex) {
  28. throw ex;
  29. }
  30. catch (Throwable ex) {
  31. throw new BeanDefinitionStoreException(
  32. "Failed to process import candidates for configuration class [" +
  33. configurationClass.getMetadata().getClassName() + "]", ex);
  34. }
  35. });
  36. }
  37. }

getImports()方法中有两个比较核心的方法,第一个proces()方法中听过调用会加载所有的SpringBoot的自动配置类,第二个方法:selectImports(),返回EnableAutoConfigurationImportSelector

  1. public Iterable<Group.Entry> getImports() {
  2. for (DeferredImportSelectorHolder deferredImport : this.deferredImports) {
  3. this.group.process(deferredImport.getConfigurationClass().getMetadata(),
  4. deferredImport.getImportSelector());
  5. }
  6. return this.group.selectImports();
  7. }
  8. }

继续跟进this.group.process(), 具体实现类为:AutoConfigurationImportSelector

  1. public void process(AnnotationMetadata annotationMetadata, DeferredImportSelector deferredImportSelector) {
  2. Assert.state(deferredImportSelector instanceof AutoConfigurationImportSelector,
  3. () -> String.format("Only %s implementations are supported, got %s",
  4. AutoConfigurationImportSelector.class.getSimpleName(),
  5. deferredImportSelector.getClass().getName()));
  6. AutoConfigurationEntry autoConfigurationEntry = ((AutoConfigurationImportSelector) deferredImportSelector)
  7. .getAutoConfigurationEntry(getAutoConfigurationMetadata(), annotationMetadata);
  8. this.autoConfigurationEntries.add(autoConfigurationEntry);
  9. for (String importClassName : autoConfigurationEntry.getConfigurations()) {
  10. this.entries.putIfAbsent(importClassName, annotationMetadata);
  11. }
  12. }

继续跟进getAutoConfigurationEntry()方法,在此方法中将会看到加载了SpringBoot 中定义的全部配置类,然后进行排除等处理得到最后真正需要使用的配置类

  1. protected AutoConfigurationEntry getAutoConfigurationEntry(AutoConfigurationMetadata autoConfigurationMetadata,
  2. AnnotationMetadata annotationMetadata) {
  3. if (!isEnabled(annotationMetadata)) {
  4. return EMPTY_ENTRY;
  5. }
  6. AnnotationAttributes attributes = getAttributes(annotationMetadata);
  7. // 获取得到springboot 定义的全部自动配置项
  8. List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);
  9. configurations = removeDuplicates(configurations);
  10. Set<String> exclusions = getExclusions(annotationMetadata, attributes);
  11. checkExcludedClasses(configurations, exclusions);
  12. configurations.removeAll(exclusions);
  13. configurations = filter(configurations, autoConfigurationMetadata);
  14. fireAutoConfigurationImportEvents(configurations, exclusions);
  15. return new AutoConfigurationEntry(configurations, exclusions);
  16. }

获取得到SpringBoot 在sprig.factories 文件中配置的全部配置项

  1. protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
  2. List<String> configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(),
  3. getBeanClassLoader());
  4. Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you "
  5. + "are using a custom packaging, make sure that file is correct.");
  6. return configurations;
  7. }
  8. protected Class<?> getSpringFactoriesLoaderFactoryClass() {
  9. // 定义在sprig.factories 中的配置项
  10. return EnableAutoConfiguration.class;
  11. }

configurations集合大小就是SpringBoot 定义的全部和项目中的自定义对象,从全部124个到处理之后只有58个对象如下图:
image.png
image.png
上面分析说过getImports()中有两个核心方法,看完第一个proces()方法,接下来我继续跟进selectImports()方法

  1. public Iterable<Entry> selectImports() {
  2. if (this.autoConfigurationEntries.isEmpty()) {
  3. return Collections.emptyList();
  4. }
  5. Set<String> allExclusions = this.autoConfigurationEntries.stream()
  6. .map(AutoConfigurationEntry::getExclusions).flatMap(Collection::stream).collect(Collectors.toSet());
  7. Set<String> processedConfigurations = this.autoConfigurationEntries.stream()
  8. .map(AutoConfigurationEntry::getConfigurations).flatMap(Collection::stream)
  9. .collect(Collectors.toCollection(LinkedHashSet::new));
  10. processedConfigurations.removeAll(allExclusions);
  11. return sortAutoConfigurations(processedConfigurations, getAutoConfigurationMetadata()).stream()
  12. .map((importClassName) -> new Entry(this.entries.get(importClassName), importClassName))
  13. .collect(Collectors.toList());
  14. }

最后返回的配置类
image.png

在获取到springBoot提供的配置后,再次调用processImports方法进行递归解析,根据我们自定义的配置文件,进行选择性配置。
这么多的配置类,不可能全部进行加载,项目也用不了这么多。选择的规则是什么呢?

三、如何内嵌tomcat