SpringBoot系列之【启动流程详解】


SpringBoot版本:2.1.0

前言

几年前初出茅庐时,获得了一个心仪大厂的面试邀约,面试前准备万分,即使信心十足,面试当场还是有些紧张,导致发挥不如预期,至今仍有些许遗憾。(*>﹏<*)

这个【SpringBoot启动流程】就是当初没回答好的部分,这次来补上,机会虽然错过,但知识绝不能错过,以下整理相关知识点。

一、SpringBoot特点

这边先简单扼要叙述一下SpringBoot的强大之处:

  • 可以创建独立的Spring应用程序,并且基于其Maven或Gradle插件,可以创建可执行的JARs和WARs
  • 内嵌Tomcat或Jetty等Servlet容器
  • 提供自动配置的“starter”项目对象模型(POMS)以简化Maven配置
  • 尽可能自动配置Spring容器
  • 提供准备好的特性,如指标、健康检查和外部化配置
  • 绝对没有代码生成,不需要XML配置。

二、SpringBoot启动流程图

让我们先来看看SpringBoot的启动流程图,如下图所示:
在这里插入图片描述

三、SpringBoot启动类入口

用过SpringBoot的技术人员很显而易见的两者之间的差别就是视觉上很直观的:SpringBoot有自己独立的启动类(独立程序)

@SpringBootApplication
public class ServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(ServiceApplication.class, args);
    }
}

这段代码的核心为注解定义(@SpringBootApplication)和类定义(SpringApplication.run

1.注解:@SpringBootApplication

注解内部源码如下:

@Target({ElementType.TYPE}) // 注解的适用范围,其中TYPE用于描述类、接口(包括包注解类型)或enum声明
@Retention(RetentionPolicy.RUNTIME) // 注解的生命周期,保留到class文件中(三个生命周期)
@Documented // 表明这个注解应该被javadoc记录
@Inherited // 子类可以继承该注解
@SpringBootConfiguration // 继承了Configuration,表示当前是注解类
@EnableAutoConfiguration // 开启springboot的注解功能,springboot的四大神器之一,其借助@import的帮助
@ComponentScan(excludeFilters = {@Filter( // 扫描路径设置
    type = FilterType.CUSTOM,
    classes = {TypeExcludeFilter.class}
), @Filter(
    type = FilterType.CUSTOM,
    classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {
...
}

在其中比较重要的有三个注解,分别是:

  1. @SpringBootConfiguration
  2. @EnableAutoConfiguration
  3. @ComponentScan

下面先来说说第一个注解:

@SpringBootConfiguration

根据Javadoc可知,该注解作用就是将当前的类作为一个JavaConfig,然后触发注解@EnableAutoConfiguration和@ComponentScan的处理,本质上与@Configuration注解没有区别

Java Configuration的配置形式注入bean,参考以下代码:

@Configuration
public class FakeConfiguration{
    @Bean
    public FakeService mockService(){
        return new FakeServiceImpl();
    }
}

@Configuration标注当前类是Java Config配置类,会被扫描并加载到IoC容器。

这边额外简单补充一下 @Configuration@Component的区别:

  1. @Component注解的范围最广,所有类都可以注解,而 @Configuration一般注解在这样的类上:这个类里面有 @Value注解的成员变量和@Bean注解的方法,就是一个配置类。
  2. 英语字面上意义不同,Configuration为配置,Component为组件,都定义在类的上方,也代表着此类声明的意义。

@EnableAutoConfiguration

此注解顾名思义是可以自动配置,所以应该是springboot中最为重要的注解

在spring框架中就提供了各种以@Enable开头的注解,例如: @EnableScheduling、@EnableCaching、@EnableMBeanExport等; @EnableAutoConfiguration的理念和做事方式其实一脉相承简单概括一下就是,借助@Import的支持,收集和注册特定场景相关的bean定义

  • @EnableScheduling是通过@Import将Spring调度框架相关的bean定义都加载到IoC容器【定时任务、时间调度任务】
  • @EnableMBeanExport是通过@Import将JMX相关的bean定义加载到IoC容器【监控JVM运行时状态】

@EnableAutoConfiguration也是借助@Import的帮助,将所有符合自动配置条件的bean定义加载到IoC容器。

@EnableAutoConfiguration作为一个复合注解,其自身定义关键信息如下:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage 【重点注解】
@Import({AutoConfigurationImportSelector.class}) 【重点注解】
public @interface EnableAutoConfiguration {
    String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";
    Class<?>[] exclude() default {};
    String[] excludeName() default {};
}

还有其中比较重要的一个类就是:AutoConfigurationImportSelector.class

  • @AutoConfigurationPackage
    • 注册当前启动类的根 package
    • 注册 org.springframework.boot.autoconfigure.AutoConfigurationPackagesBean 的定义。
  • @Import(AutoConfigurationImportSelector.class)
    • 可以看到实现了 DeferredImportSelector 接口,该接口继承自 ImportSelector,根据 Javadoc 可知,多用于导入被 @Conditional 注解的Bean,之后会进行 filter 操作
    • AutoConfigurationImportSelector.AutoConfigurationGroup#process 方法,SpringBoot 启动时会调用该方法,进行自动装配
      • SpringApplication#run(java.lang.String…)
      • SpringApplication#refreshContext(即 Spring IOC 容器初始化的过程中)
      • ConfigurationClassParser#parse
      • AutoConfigurationImportSelector.AutoConfigurationGroup#process
  • 通过 SpringFactoriesLoader#loadFactoryNames 获取应考虑的自动配置名称。
  • 通过 filter 过滤掉当前环境不需要自动装配的类,各种 @Conditional 不满足就被过滤掉。
  • 需要自动装配的全路径类名注册到 SpringIOC 容器,自此 SpringBoot 自动装配完成

SpringBoot 自动装配的核心注解,在 Spring 框架中就提供了各种以 @Enable 开头的注解,例如: @EnableCircuitBreaker@EnableScheduling 等;

@ComponentScan

  • ComponentScan的功能其实就是自动扫描并加载符合条件的组件(比如@Component@Repository等)或者bean定义。
  • 我们可以通过 basePackages 等属性来细粒度的定制 @ComponentScan 自动扫描的范围,如果不指定,则默认Spring框架实现会从声明 @ComponentScan 所在类的package进行扫描,所以 SpringBoot 的启动类最好是放在根package下,我们自定义的类就放在对应的子package下,这样就可以不指定 basePackages

2.main方法

main方法里调用org.springframework.boot.SpringApplication.run(java.lang.Class<?>, java.lang.String…)方法。

SpringApplication#run

调用另外一个同名的重载方法run

public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
	return run(new Class<?>[] { primarySource }, args);
}

实例化SpringApplication对象

  1. 首先会实例化SpringApplication一个对象。
  2. 构造方法里初始化一些属性,比如webApplicationType,比如"SERVLET",初始化一些listeners
public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
	return new SpringApplication(primarySources).run(args);
}
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
	this.resourceLoader = resourceLoader;
	Assert.notNull(primarySources, "PrimarySources must not be null");
	this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
	this.webApplicationType = WebApplicationType.deduceFromClasspath();
	setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
	setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
	this.mainApplicationClass = deduceMainApplicationClass();
}

SpringApplication.run(java.lang.String…)

经典的观察者模式

  1. 创建一个StopWatch实例,用来记录SpringBoot的启动时间。
  2. 通过SpringFactoriesLoader加载listeners:比如EventPublishingRunListener。
  3. 发布SprintBoot开始启动事件(EventPublishingRunListener#starting())。
  4. 创建和配置environment(environmentPrepared())。
  5. 打印SpringBoot的banner和版本。
  6. 创建对应的ApplicationContext:Web类型,Reactive类型,普通的类型(非Web)。
  7. prepareContext:
    1. 准备ApplicationContext,Initializers设置到ApplicationContext(contextPrepared())。
    2. 打印启动日志,打印profile信息(如dev, test, prod)。
    3. 最终会调用到AbstractApplicationContext#refresh方法,实际上就是Spring IOC容器的创建过程,并且会进行自动装配的操作,以及发布ApplicationContext已经refresh事件,标志着ApplicationContext初始化完成(contextLoaded())
  8. afterRefresh hook方法。
  9. stopWatch停止计时,日志打印总共启动的时间。
  10. 发布SpringBoot程序已启动事件(started())。
  11. 调用ApplicationRunner和CommandLineRunner。
  12. 最后发布就绪事件ApplicationReadyEvent,标志着SpringBoot可以处理就收的请求了(running())。
public ConfigurableApplicationContext run(String... args) {
    // 创建一个StopWatch实例,用来记录SpringBoot的启动时间
 StopWatch stopWatch = new StopWatch();
 stopWatch.start();
 ConfigurableApplicationContext context = null;
 Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
 configureHeadlessProperty();
    // 通过SpringFactoriesLoader加载listeners:比如EventPublishingRunListener
 SpringApplicationRunListeners listeners = getRunListeners(args);
    // 发布SprintBoot启动事件:ApplicationStartingEvent
 listeners.starting();
 try {
  ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
     // 创建和配置environment,发布事件:SpringApplicationRunListeners#environmentPrepared
  ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
  configureIgnoreBeanInfo(environment);
     // 打印SpringBoot的banner和版本
  Banner printedBanner = printBanner(environment);
     // 创建对应的ApplicationContext:Web类型,Reactive类型,普通的类型(非Web)
  context = createApplicationContext();
  exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
    new Class[] { ConfigurableApplicationContext.class }, context);
     // 准备ApplicationContext,Initializers设置到ApplicationContext后发布事件:ApplicationContextInitializedEvent
     // 打印启动日志,打印profile信息(如dev, test, prod)
     // 调用EventPublishingRunListener发布ApplicationContext加载完毕事件:ApplicationPreparedEvent
  prepareContext(context, environment, listeners, applicationArguments, printedBanner);
     // 最终会调用到AbstractApplicationContext#refresh方法,实际上就是Spring IOC容器的创建过程,并且会进行自动装配的操作
     // 以及发布ApplicationContext已经refresh事件,标志着ApplicationContext初始化完成
  refreshContext(context);
     // hook方法
  afterRefresh(context, applicationArguments);
     // stopWatch停止计时,日志打印总共启动的时间
  stopWatch.stop();
  if (this.logStartupInfo) {
   new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
  }
     // 发布SpringBoot程序已启动事件ApplicationStartedEvent
  listeners.started(context);
     // 调用ApplicationRunner和CommandLineRunner
  callRunners(context, applicationArguments);
 }
 catch (Throwable ex) {
  handleRunFailure(context, ex, exceptionReporters, listeners);
  throw new IllegalStateException(ex);
 }

 try {
     // 最后发布就绪事件ApplicationReadyEvent,标志着SpringBoot可以处理就收的请求了
  listeners.running(context);
 }
 catch (Throwable ex) {
  handleRunFailure(context, ex, exceptionReporters, null);
  throw new IllegalStateException(ex);
 }
 return context;
}

三、SpringBoot启动事件

  • SpringApplicationRunListeners的唯一实现是EventPublishingRunListener。
  • 整个SpringBoot的启动,流程就是各种事件的发布,调用EventPublishingRunListener中的方法。
  • 只要明白了EventPublishingRunListener中事件发布的流程,也就明白了SpringBoot启动的大体流程。

EventPublishingRunListener

方法说明如下:

public class EventPublishingRunListener implements SpringApplicationRunListener, Ordered {

 private final SpringApplication application;

 private final String[] args;

 private final SimpleApplicationEventMulticaster initialMulticaster;

 public EventPublishingRunListener(SpringApplication application, String[] args) {
  this.application = application;
  this.args = args;
  this.initialMulticaster = new SimpleApplicationEventMulticaster();
  for (ApplicationListener<?> listener : application.getListeners()) {
   this.initialMulticaster.addApplicationListener(listener);
  }
 }

 @Override
 public int getOrder() {
  return 0;
 }

    // SpringBoot启动事件
 @Override
 public void starting() {
  this.initialMulticaster.multicastEvent(new ApplicationStartingEvent(this.application, this.args));
 }

    // 创建和配置环境
 @Override
 public void environmentPrepared(ConfigurableEnvironment environment) {
  this.initialMulticaster
    .multicastEvent(new ApplicationEnvironmentPreparedEvent(this.application, this.args, environment));
 }

    // 准备ApplicationContext
 @Override
 public void contextPrepared(ConfigurableApplicationContext context) {
  this.initialMulticaster
    .multicastEvent(new ApplicationContextInitializedEvent(this.application, this.args, context));
 }

    // 发布ApplicationContext已经refresh事件,标志着ApplicationContext初始化完成
 @Override
 public void contextLoaded(ConfigurableApplicationContext context) {
  for (ApplicationListener<?> listener : this.application.getListeners()) {
   if (listener instanceof ApplicationContextAware) {
    ((ApplicationContextAware) listener).setApplicationContext(context);
   }
   context.addApplicationListener(listener);
  }
  this.initialMulticaster.multicastEvent(new ApplicationPreparedEvent(this.application, this.args, context));
 }

    // SpringBoot已启动事件
 @Override
 public void started(ConfigurableApplicationContext context) {
  context.publishEvent(new ApplicationStartedEvent(this.application, this.args, context));
  AvailabilityChangeEvent.publish(context, LivenessState.CORRECT);
 }

    // "SpringBoot现在可以处理接受的请求"事件
 @Override
 public void running(ConfigurableApplicationContext context) {
  context.publishEvent(new ApplicationReadyEvent(this.application, this.args, context));
  AvailabilityChangeEvent.publish(context, ReadinessState.ACCEPTING_TRAFFIC);
 }

 @Override
 public void failed(ConfigurableApplicationContext context, Throwable exception) {
  ApplicationFailedEvent event = new ApplicationFailedEvent(this.application, this.args, context, exception);
  if (context != null && context.isActive()) {
   // Listeners have been registered to the application context so we should
   // use it at this point if we can
   context.publishEvent(event);
  }
  else {
   // An inactive context may not have a multicaster so we use our multicaster to
   // call all of the context's listeners instead
   if (context instanceof AbstractApplicationContext) {
    for (ApplicationListener<?> listener : ((AbstractApplicationContext) context)
      .getApplicationListeners()) {
     this.initialMulticaster.addApplicationListener(listener);
    }
   }
   this.initialMulticaster.setErrorHandler(new LoggingErrorHandler());
   this.initialMulticaster.multicastEvent(event);
  }
 }

 private static class LoggingErrorHandler implements ErrorHandler {

  private static final Log logger = LogFactory.getLog(EventPublishingRunListener.class);

  @Override
  public void handleError(Throwable throwable) {
   logger.warn("Error calling ApplicationEventListener", throwable);
  }
 }
}

四、SpringIOC 容器初始化过程

由于现在大都是用SpringBoot开发,所以呢,Spring IOC 初始化的源码,就是AnnotationConfigApplicationContext中的源码,IoC的初始化就是该类实例创建的过程

创建的过程 (AnnotationConfigApplicationContext的构造方法)

  1. 给我们的Bean,创建与之对应的Bean定义,然后把他们放入 ConcurrentHashMap(key:beanName和value:beanDefinition)中;Bean定义实际上包括一些Bean的信息,比如BeanName, Scope, 是否被@Primary注解修饰,是否是@Lazy,以及@Description等注解。
  2. refresh()方法: 创建IOC需要的资源
  3. 初始化BeanFactory, set一些属性,如BeanClassLoadersystemEnvironment
  4. 如果是SpringBoot程序,会调用方法进行自动装配:AutoConfigurationImportSelector.AutoConfigurationGroup#process。
  5. 注册MessageSource,国际化相关的资源,到ApplicationContext。
  6. 注册ApplicationListener到ApplicationContext。
  7. 实例化化lazy-init的Bean。
  8. 最后,publish相关的事件,ApplicationContext 就初始化完成,整个IOC容器初始化完成(IOC容器的本质就是初始化BeanFactory和ApplicationContext),就可以从IOC容器中获取Bean自动注入了。

五、结语

已经工作了一段时间了,回头看看这些知识点,发现自己仍有许多不足之处,通过这次学习,不再让自己停留在“会用”的阶段,而是进一步理解其中原理,注重实践,自己还是得抓紧脚步跟上大佬的脚步。(☆_☆)

在这里插入图片描述

  • 42
    点赞
  • 125
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 28
    评论
Spring Boot启动流程可以分为以下几个步骤: 1. 应用主入口:Spring Boot的应用主入口是一个标有@SpringBootApplication注解的类。在启动过程中,它会被作为启动类加载到内存中。 2. 配置形式:Spring Boot提供了多种配置Bean的形式。首先是通过定义Bean的方式,在应用主入口类中使用@Bean注解来定义Bean。其次是通过@Configuration类配置方式,在应用主入口类外创建一个专门用于配置Bean的类,并在该类中使用@Bean注解来定义Bean。还有一种方式是通过Spring XML配置文件进行配置。最后,还可以通过自动配置类来配置Bean,这些自动配置类是Spring Boot内部提供的,会根据配置文件和依赖自动完成一些配置工作。 3. 启动流程:在启动阶段,Spring Boot会依次执行以下步骤: - 加载Spring Boot的核心配置文件和依赖的配置文件。 - 创建并初始化Spring的ApplicationContext容器。 - 执行各个自动配置类,完成自动配置工作。 - 执行应用主入口类中的初始化方法,并启动Spring Boot应用。 4. Bean定义加载顺序:在Spring Boot启动过程中,Bean的加载顺序非常重要。如果在主线程加载Bean的同时,有异步线程进行Dubbo调用或加载Bean,可能会导致死锁。为了避免这种情况,应该保证只有一个线程在进行Spring加载Bean的操作。可以在Spring启动完成后再进行异步初始化操作,或者使用Spring的事件机制,在订阅ApplicationStartedEvent事件后再执行异步初始化操作。 综上所述,Spring Boot启动流程包括应用主入口、配置形式、启动流程和Bean定义加载顺序。在启动过程中,需要注意Bean的加载顺序,以避免死锁情况的发生。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 28
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

愛彈吉他的小盆友

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值