热门标签 | HotTags
当前位置:  开发笔记 > 运维 > 正文

通过代码实例了解SpringBoot启动原理

这篇文章主要介绍了通过代码实例了解SpringBoot启动原理,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

这篇文章主要介绍了通过代码实例了解SpringBoot启动原理,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

SpringBoot和Spring相比,有着不少优势,比如自动配置,jar直接运行等等。那么SpringBoot到底是怎么启动的呢?

下面是SpringBoot启动的入口:

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

一、先看一下@SpringBoot注解:

@Target({ElementType.TYPE})  //定义其使用时机
@Retention(RetentionPolicy.RUNTIME) //编译程序将Annotation储存于class档中,可由VM使用反射机制的代码所读取和使用。
@Documented //这个注解应该被 javadoc工具记录
@Inherited //被注解的类会自动继承. 更具体地说,如果定义注解时使用了 @Inherited 标记,然后用定义的注解来标注另一个父类, 父类又有一个子类(subclass),则父类的所有属性将被继承到它的子类中.
@SpringBootConfiguration //@SpringBootConfiguration就相当于@Configuration。JavaConfig配置形式
@EnableAutoConfiguration
@ComponentScan(
  excludeFilters = {@Filter(
  type = FilterType.CUSTOM,
  classes = {TypeExcludeFilter.class}
), @Filter(
  type = FilterType.CUSTOM,
  classes = {AutoConfigurationExcludeFilter.class}
)} //自动扫描并加载符合条件的组件。以通过basePackages等属性来细粒度的定制@ComponentScan自动扫描的范围,如果不指定,则默认Spring框架实现会从声明@ComponentScan所在类的package进行扫描。
注:所以SpringBoot的启动类最好是放在root package下,因为默认不指定basePackages。
)
public @interface SpringBootApplication {
  @AliasFor(
    annotation = EnableAutoConfiguration.class
  )
  Class<&#63;>[] exclude() default {};

  @AliasFor(
    annotation = EnableAutoConfiguration.class
  )
  String[] excludeName() default {};

  @AliasFor(
    annotation = ComponentScan.class,
    attribute = "basePackages"
  )
  String[] scanBasePackages() default {};

  @AliasFor(
    annotation = ComponentScan.class,
    attribute = "basePackageClasses"
  )
  Class<&#63;>[] scanBasePackageClasses() default {};
}

所以,实际上SpringBootApplication注解相当于三个注解的组合,@SpringBootConfiguration,@ComponentScan和@EnableAutoConfiguration。

@SpringBootConfiguration和@ComponentScan,很容易知道它的意思,一个是JavaConfig配置,一个是扫描包。关键在于@EnableAutoConfiguration注解。先来看一下这个注解:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import({AutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {
  String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";

  Class<&#63;>[] exclude() default {};

  String[] excludeName() default {};
}

Springboot应用启动过程中使用ConfigurationClassParser分析配置类时,如果发现注解中存在@Import(ImportSelector)的情况,就会创建一个相应的ImportSelector对象, 并调用其方法 public String[] selectImports(AnnotationMetadata annotationMetadata), 这里 EnableAutoConfigurationImportSelector的导入@Import(EnableAutoConfigurationImportSelector.class) 就属于这种情况,所以ConfigurationClassParser会实例化一个 EnableAutoConfigurationImportSelector 并调用它的 selectImports() 方法。

AutoConfigurationImportSelector implements DeferredImportSelector extends ImportSelector。

下面是AutoConfigurationImportSelector的执行过程:

public class AutoConfigurationImportSelector implements DeferredImportSelector, BeanClassLoaderAware, ResourceLoaderAware, BeanFactoryAware, EnvironmentAware, Ordered {
  private static final String[] NO_IMPORTS = new String[0];
  private static final Log logger = LogFactory.getLog(AutoConfigurationImportSelector.class);
  private static final String PROPERTY_NAME_AUTOCONFIGURE_EXCLUDE = "spring.autoconfigure.exclude";
  private ConfigurableListableBeanFactory beanFactory;
  private Environment environment;
  private ClassLoader beanClassLoader;
  private ResourceLoader resourceLoader;
  public AutoConfigurationImportSelector() {
  }

  public String[] selectImports(AnnotationMetadata annotationMetadata) {
    if (!this.isEnabled(annotationMetadata)) {
      return NO_IMPORTS;
    } else {
      // 从配置文件中加载 AutoConfigurationMetadata
      AutoConfigurationMetadata autoCOnfigurationMetadata= AutoConfigurationMetadataLoader.loadMetadata(this.beanClassLoader);
      AnnotationAttributes attributes = this.getAttributes(annotationMetadata);
      // 获取所有候选配置类EnableAutoConfiguration
      // 使用了内部工具使用SpringFactoriesLoader,查找classpath上所有jar包中的
      // META-INF\spring.factories,找出其中key为
      // org.springframework.boot.autoconfigure.EnableAutoConfiguration 
      // 的属性定义的工厂类名称。
      // 虽然参数有annotationMetadata,attributes,但在 AutoConfigurationImportSelector 的
      // 实现 getCandidateConfigurations()中,这两个参数并未使用
      List cOnfigurations= this.getCandidateConfigurations(annotationMetadata, attributes);
      //去重
      cOnfigurations= this.removeDuplicates(configurations);
      Set exclusiOns= this.getExclusions(annotationMetadata, attributes);
      // 应用 exclusion 属性
      this.checkExcludedClasses(configurations, exclusions);
      configurations.removeAll(exclusions);
      // 应用过滤器AutoConfigurationImportFilter,
      // 对于 spring boot autoconfigure,定义了一个需要被应用的过滤器 :
      // org.springframework.boot.autoconfigure.condition.OnClassCondition,
      // 此过滤器检查候选配置类上的注解@ConditionalOnClass,如果要求的类在classpath
      // 中不存在,则这个候选配置类会被排除掉
      cOnfigurations= this.filter(configurations, autoConfigurationMetadata);
     // 现在已经找到所有需要被应用的候选配置类
     // 广播事件 AutoConfigurationImportEvent
      this.fireAutoConfigurationImportEvents(configurations, exclusions);
      return StringUtils.toStringArray(configurations);
    }
  }

  protected AnnotationAttributes getAttributes(AnnotationMetadata metadata) {
    String name = this.getAnnotationClass().getName();
    AnnotationAttributes attributes = AnnotationAttributes.fromMap(metadata.getAnnotationAttributes(name, true));
    Assert.notNull(attributes, () -> {
      return "No auto-configuration attributes found. Is " + metadata.getClassName() + " annotated with " + ClassUtils.getShortName(name) + "&#63;";
    });
    return attributes;
  }

  protected List getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
    List cOnfigurations= SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader());
    Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you are using a custom packaging, make sure that file is correct.");
    return configurations;
  }


public abstract class SpringFactoriesLoader {
  public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";
  private static final Log logger = LogFactory.getLog(SpringFactoriesLoader.class);
  private static final Map> cache = new ConcurrentReferenceHashMap();

  public SpringFactoriesLoader() {
  }
    public static List loadFactoryNames(Class<&#63;> factoryClass, @Nullable ClassLoader classLoader) {
    String factoryClassName = factoryClass.getName();
    return (List)loadSpringFactories(classLoader).getOrDefault(factoryClassName, Collections.emptyList());
  }
}

  private List filter(List configurations, AutoConfigurationMetadata autoConfigurationMetadata) {
    long startTime = System.nanoTime();
    String[] candidates = StringUtils.toStringArray(configurations);
    // 记录候选配置类是否需要被排除,skip为true表示需要被排除,全部初始化为false,不需要被排除
    boolean[] skip = new boolean[candidates.length];
    // 记录候选配置类中是否有任何一个候选配置类被忽略,初始化为false
    boolean skipped = false;
    Iterator var8 = this.getAutoConfigurationImportFilters().iterator();
    // 获取AutoConfigurationImportFilter并逐个应用过滤
    while(var8.hasNext()) {
      AutoConfigurationImportFilter filter = (AutoConfigurationImportFilter)var8.next();
      // 对过滤器注入其需要Aware的信息
      this.invokeAwareMethods(filter);
      // 使用此过滤器检查候选配置类跟autoConfigurationMetadata的匹配情况
      boolean[] match = filter.match(candidates, autoConfigurationMetadata);

      for(int i = 0; i  result = new ArrayList(candidates.length);

      int numberFiltered;
      for(numberFiltered = 0; numberFiltered  getAutoConfigurationImportFilters() {
    return SpringFactoriesLoader.loadFactories(AutoConfigurationImportFilter.class, this.beanClassLoader);
  }

二、下面看一下SpringBoot启动时run方法执行过程

public ConfigurableApplicationContext run(String... args) {
  StopWatch stopWatch = new StopWatch();
  stopWatch.start();
  ConfigurableApplicationContext cOntext= null;
  Collection exceptiOnReporters= new ArrayList<>();
  this.configureHeadlessProperty();
  //从类路径下META-INF/spring.factories获取 
  SpringApplicationRunListeners listeners = getRunListeners(args);
  //回调所有的获取SpringApplicationRunListener.starting()方法
  listeners.starting();
  try {
    //封装命令行参数
    ApplicationArguments applicatiOnArguments= new DefaultApplicationArguments(
          args);
    //准备环境 
    ConfigurableEnvironment envirOnment= prepareEnvironment(listeners,
          applicationArguments);
    //创建环境完成后回调 
    SpringApplicationRunListener.environmentPrepared();表示环境准备完成
    this.configureIgnoreBeanInfo(environment);
    //打印Banner图
    Banner printedBanner = printBanner(environment);
    //创建ApplicationContext,决定创建web的ioc还是普通的ioc 
    cOntext= createApplicationContext();
    //异常分析报告
    exceptiOnReporters= getSpringFactoriesInstances(
          SpringBootExceptionReporter.class,
          new Class[] { ConfigurableApplicationContext.class }, context);
    //准备上下文环境,将environment保存到ioc中
    //applyInitializers():回调之前保存的所有的ApplicationContextInitializer的initialize方法 
    //listeners.contextPrepared(context) 
    //prepareContext运行完成以后回调所有的SpringApplicationRunListener的contextLoaded()
    this.prepareContext(context, environment, listeners, applicationArguments,
          printedBanner);
    //刷新容器,ioc容器初始化(如果是web应用还会创建嵌入式的Tomcat)
    //扫描,创建,加载所有组件的地方,(配置类,组件,自动配置)
    this.refreshContext(context);
    this.afterRefresh(context, applicationArguments);
    stopWatch.stop();
    if (this.logStartupInfo) {
      new StartupInfoLogger(this.mainApplicationClass)
              .logStarted(getApplicationLog(), stopWatch);
    }
    //所有的SpringApplicationRunListener回调started方法
    listeners.started(context);
    //从ioc容器中获取所有的ApplicationRunner和CommandLineRunner进行回调,
    //ApplicationRunner先回调,CommandLineRunner再回调
    this.callRunners(context, applicationArguments);
  }
  catch (Throwable ex) {
    this.handleRunFailure(context, ex, exceptionReporters, listeners);
    throw new IllegalStateException(ex);
  }
  try {
    //所有的SpringApplicationRunListener回调running方法
    listeners.running(context);
  }
  catch (Throwable ex) {
    this.handleRunFailure(context, ex, exceptionReporters, null);
    throw new IllegalStateException(ex);
  }
  //整个SpringBoot应用启动完成以后返回启动的ioc容器
  return context;
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


推荐阅读
  • 本文介绍了Web学习历程记录中关于Tomcat的基本概念和配置。首先解释了Web静态Web资源和动态Web资源的概念,以及C/S架构和B/S架构的区别。然后介绍了常见的Web服务器,包括Weblogic、WebSphere和Tomcat。接着详细讲解了Tomcat的虚拟主机、web应用和虚拟路径映射的概念和配置过程。最后简要介绍了http协议的作用。本文内容详实,适合初学者了解Tomcat的基础知识。 ... [详细]
  • Tomcat/Jetty为何选择扩展线程池而不是使用JDK原生线程池?
    本文探讨了Tomcat和Jetty选择扩展线程池而不是使用JDK原生线程池的原因。通过比较IO密集型任务和CPU密集型任务的特点,解释了为何Tomcat和Jetty需要扩展线程池来提高并发度和任务处理速度。同时,介绍了JDK原生线程池的工作流程。 ... [详细]
  • 标题: ... [详细]
  • Oracle优化新常态的五大禁止及其性能隐患
    本文介绍了Oracle优化新常态中的五大禁止措施,包括禁止外键、禁止视图、禁止触发器、禁止存储过程和禁止JOB,并分析了这些禁止措施可能带来的性能隐患。文章还讨论了这些禁止措施在C/S架构和B/S架构中的不同应用情况,并提出了解决方案。 ... [详细]
  • Spring常用注解(绝对经典),全靠这份Java知识点PDF大全
    本文介绍了Spring常用注解和注入bean的注解,包括@Bean、@Autowired、@Inject等,同时提供了一个Java知识点PDF大全的资源链接。其中详细介绍了ColorFactoryBean的使用,以及@Autowired和@Inject的区别和用法。此外,还提到了@Required属性的配置和使用。 ... [详细]
  • Servlet多用户登录时HttpSession会话信息覆盖问题的解决方案
    本文讨论了在Servlet多用户登录时可能出现的HttpSession会话信息覆盖问题,并提供了解决方案。通过分析JSESSIONID的作用机制和编码方式,我们可以得出每个HttpSession对象都是通过客户端发送的唯一JSESSIONID来识别的,因此无需担心会话信息被覆盖的问题。需要注意的是,本文讨论的是多个客户端级别上的多用户登录,而非同一个浏览器级别上的多用户登录。 ... [详细]
  • Spring框架《一》简介
    Spring框架《一》1.Spring概述1.1简介1.2Spring模板二、IOC容器和Bean1.IOC和DI简介2.三种通过类型获取bean3.给bean的属性赋值3.1依赖 ... [详细]
  • 本文介绍了高校天文共享平台的开发过程中的思考和规划。该平台旨在为高校学生提供天象预报、科普知识、观测活动、图片分享等功能。文章分析了项目的技术栈选择、网站前端布局、业务流程、数据库结构等方面,并总结了项目存在的问题,如前后端未分离、代码混乱等。作者表示希望通过记录和规划,能够理清思路,进一步完善该平台。 ... [详细]
  • 本文介绍了关于apache、phpmyadmin、mysql、php、emacs、path等知识点,以及如何搭建php环境。文章提供了详细的安装步骤和所需软件列表,希望能帮助读者解决与LAMP相关的技术问题。 ... [详细]
  • PHPMailer邮件类邮件发送功能的使用教学及注意事项
    本文介绍了使用国外开源码PHPMailer邮件类实现邮件发送功能的简单教学,同时提供了一些注意事项。文章涵盖了字符集设置、发送HTML格式邮件、群发邮件以及避免类的重定义等方面的内容。此外,还提供了一些与PHP相关的资源和服务,如传奇手游游戏源码下载、vscode字体调整、数据恢复、Ubuntu实验环境搭建、北京爬虫市场、进阶PHP和SEO人员需注意的内容。 ... [详细]
  • 开发笔记:Java是如何读取和写入浏览器Cookies的
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了Java是如何读取和写入浏览器Cookies的相关的知识,希望对你有一定的参考价值。首先我 ... [详细]
  • r2dbc配置多数据源
    R2dbc配置多数据源问题根据官网配置r2dbc连接mysql多数据源所遇到的问题pom配置可以参考官网,不过我这样配置会报错我并没有这样配置将以下内容添加到pom.xml文件d ... [详细]
  • 本文总结了淘淘商城项目的功能和架构,并介绍了传统架构中遇到的session共享问题及解决方法。淘淘商城是一个综合性的B2C平台,类似京东商城、天猫商城,会员可以在商城浏览商品、下订单,管理员、运营可以在平台后台管理系统中管理商品、订单、会员等。商城的架构包括后台管理系统、前台系统、会员系统、订单系统、搜索系统和单点登录系统。在传统架构中,可以采用tomcat集群解决并发量高的问题,但由于session共享的限制,集群数量有限。本文探讨了如何解决session共享的问题。 ... [详细]
  • 本文介绍了互联网思维中的三个段子,涵盖了餐饮行业、淘品牌和创业企业的案例。通过这些案例,探讨了互联网思维的九大分类和十九条法则。其中包括雕爷牛腩餐厅的成功经验,三只松鼠淘品牌的包装策略以及一家创业企业的销售额增长情况。这些案例展示了互联网思维在不同领域的应用和成功之道。 ... [详细]
  • OpenMap教程4 – 图层概述
    本文介绍了OpenMap教程4中关于地图图层的内容,包括将ShapeLayer添加到MapBean中的方法,OpenMap支持的图层类型以及使用BufferedLayer创建图像的MapBean。此外,还介绍了Layer背景标志的作用和OMGraphicHandlerLayer的基础层类。 ... [详细]
author-avatar
mobiledu2502869373
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有