在使用SpringBoot之后,启动一个应用变得非常简单。但作为一个有追求的技术人,不仅要会用,还要了解其基本原理。

下面是一个启动类例子,由三部分组成:SpringBootApplication注解,main方法,run方法调用
**

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

main 方法这个没什么好说的,名字是别人定好的,启动的时候会执行这个方法。

SpringBootApplication注解

  1. @Target({ElementType.TYPE})
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Documented
  4. @Inherited
  5. @SpringBootConfiguration
  6. @EnableAutoConfiguration
  7. @ComponentScan(
  8. excludeFilters = {@Filter(
  9. type = FilterType.CUSTOM,
  10. classes = {TypeExcludeFilter.class}
  11. ), @Filter(
  12. type = FilterType.CUSTOM,
  13. classes = {AutoConfigurationExcludeFilter.class}
  14. )}
  15. )
  16. public @interface SpringBootApplication {
  17. //忽略其它代码
  18. }

SpringBootApplication注解其实是SpringBootConfiguration,EnableAutoConfiguration和ComponentScan的复合体。

1.SpringBootConfiguration

其实就是@Configuration,用来表示被标注的类是一个配置类,并将其加载到Spring容器中
**

2.EnableAutoConfiguration

开启SpringBoot自动配置,在程序启动时读取 ClassPath 下面的 META-INF/spring.factories 文件来获取所有导出类,生成默认配置

3.ComponentScan

包扫描注解,默认扫描主类包路径下的类

run的调用过程

run方法本质就是 new SpringApplication 实例,同时调用一下它的run方法

  1. public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
  2. return run(new Class[]{primarySource}, args);
  3. }
  4. public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
  5. return (new SpringApplication(primarySources)).run(args);
  6. }

构造函数

我们先看一下构造函数的内容

  1. public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
  2. this.resourceLoader = resourceLoader;
  3. Assert.notNull(primarySources, "PrimarySources must not be null");
  4. // 1.主类容器
  5. this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
  6. // 2.推断应用类型
  7. this.webApplicationType = WebApplicationType.deduceFromClasspath();
  8. // 3.扫描META-INF/spring.factories文件的 ApplicationContextInitializer 并加载
  9. setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
  10. // 4.扫描META-INF/spring.factories文件的 ApplicationListener 并加载
  11. setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
  12. // 5.保存主类
  13. this.mainApplicationClass = deduceMainApplicationClass();
  14. }

整个构造过程主要是加载了 ApplicationContextInitializer 和 ApplicationListener

  • ApplicationContextInitializer 初始化了 SpringBoot 上下文 Context,后面会用到
  • ApplicationListener 则是监听 SpringBoot 启动后的事件 onApplicationEvent

加载的配置和内容都在 META-INF/spring.factories 下面

run

我们再看一下实例调用的 run 方法

  1. public ConfigurableApplicationContext run(String... args) {
  2. // 1.这是一个计时器
  3. StopWatch stopWatch = new StopWatch();
  4. stopWatch.start();
  5. // 2.初始化 context
  6. ConfigurableApplicationContext context = null;
  7. // 3.给用户定制 Exception 错误提示用的,先忽略
  8. Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
  9. // 4.设置一些环境变量
  10. configureHeadlessProperty();
  11. // 5.获取事件监听器并开始监听
  12. SpringApplicationRunListeners listeners = getRunListeners(args);
  13. listeners.starting();
  14. try {
  15. // 6.把参数args封装成DefaultApplicationArguments
  16. ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
  17. // 7.准备环境信息并和 Spring 上下文绑定
  18. ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
  19. configureIgnoreBeanInfo(environment);
  20. // 8.打印banner
  21. Banner printedBanner = printBanner(environment);
  22. // 9.创建应用 context
  23. context = createApplicationContext();
  24. // 10.获取异常事件监听
  25. exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
  26. new Class[] { ConfigurableApplicationContext.class }, context);
  27. // 11.把环境信息,监听器,参数,banner和context上下文绑定
  28. prepareContext(context, environment, listeners, applicationArguments, printedBanner);
  29. // 12.刷新Context?这个命名我也比较奇怪。在这里是Spring真正的启动处,会去扫描和初始化Bean
  30. refreshContext(context);
  31. // 13.一个Refresh结束之后的钩子,什么也没做
  32. afterRefresh(context, applicationArguments);
  33. // 14.停止计时
  34. stopWatch.stop();
  35. if (this.logStartupInfo) {
  36. new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
  37. }
  38. // 15.监听器 start
  39. listeners.started(context);
  40. // 16.调用Context里面的 ApplicationRunner 和 CommandLineRunner
  41. callRunners(context, applicationArguments);
  42. }
  43. catch (Throwable ex) {
  44. handleRunFailure(context, ex, exceptionReporters, listeners);
  45. throw new IllegalStateException(ex);
  46. }
  47. try {
  48. // 15.监听器 开始运行
  49. listeners.running(context);
  50. }
  51. catch (Throwable ex) {
  52. handleRunFailure(context, ex, exceptionReporters, null);
  53. throw new IllegalStateException(ex);
  54. }
  55. return context;
  56. }

整体来说,run是在初始化上下文和绑定一些参数,环境信息等

其中最关键的是 refreshContext ,点击去发现很惊喜,这部分代码注释写得非常好,每一行都有注释…

  1. @Override
  2. public void refresh() throws BeansException, IllegalStateException {
  3. synchronized (this.startupShutdownMonitor) {
  4. // Prepare this context for refreshing.
  5. prepareRefresh();
  6. // Tell the subclass to refresh the internal bean factory.
  7. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
  8. // Prepare the bean factory for use in this context.
  9. prepareBeanFactory(beanFactory);
  10. try {
  11. // Allows post-processing of the bean factory in context subclasses.
  12. postProcessBeanFactory(beanFactory);
  13. // Invoke factory processors registered as beans in the context.
  14. invokeBeanFactoryPostProcessors(beanFactory);
  15. // Register bean processors that intercept bean creation.
  16. registerBeanPostProcessors(beanFactory);
  17. // Initialize message source for this context.
  18. initMessageSource();
  19. // Initialize event multicaster for this context.
  20. initApplicationEventMulticaster();
  21. // Initialize other special beans in specific context subclasses.
  22. // 这里很关键,在创建 web Server
  23. onRefresh();
  24. // Check for listener beans and register them.
  25. registerListeners();
  26. // Instantiate all remaining (non-lazy-init) singletons.
  27. finishBeanFactoryInitialization(beanFactory);
  28. // Last step: publish corresponding event.
  29. finishRefresh();
  30. }
  31. catch (BeansException ex) {
  32. if (logger.isWarnEnabled()) {
  33. logger.warn("Exception encountered during context initialization - " +
  34. "cancelling refresh attempt: " + ex);
  35. }
  36. // Destroy already created singletons to avoid dangling resources.
  37. destroyBeans();
  38. // Reset 'active' flag.
  39. cancelRefresh(ex);
  40. // Propagate exception to caller.
  41. throw ex;
  42. }
  43. finally {
  44. // Reset common introspection caches in Spring's core, since we
  45. // might not ever need metadata for singleton beans anymore...
  46. resetCommonCaches();
  47. }
  48. }
  49. }

总结:
1、run 方法主要是扫描配置,初始化了应用上下文并加载bean到容器
2、启动Web容器

图解

image.png

参考文章:
Using the @SpringBootApplication Annotation:https://docs.spring.io/spring-boot/docs/current/reference/html/using-spring-boot.html#using-boot-using-springbootapplication-annotation
SpringBoot启动流程总结: https://blog.csdn.net/mnicsm/article/details/93893669