zoukankan      html  css  js  c++  java
  • 【SpringBoot】SpringBoot 自动配置原理

      自动配置原理分析从@SpringBootApplication注解开始,本章使用的SpringBoot版本是2.2.5

    一、@SpringBootApplication注解  

      @SpringBootApplication注解包括了@SpringBootConfiguration、@EnableAutoConfiguration 和@ComponentScan

      @SpringBootConfiguration注解: 只是说明当前类是一个配置类,Spring初始化会将当前类做配置类处理

      @ComponentScan:扫描注解,由于没有配置basePackages属性,那么Spring扫描时,会将当前类的包路径当作扫描路径

      @EnableAutoConfiguration:开启自动配置,启动导入类2个类 AutoConfigurationPackages.Registrar.class 和 AutoConfigurationImportSelector.class

    @SpringBootApplication注解如下:

     1 // 注解类型(类、接口、或者枚举)
     2 @Target(ElementType.TYPE)
     3 // 保留策略(运行时有效)
     4 @Retention(RetentionPolicy.RUNTIME)
     5 // java doc 会生成注解信息
     6 @Documented
     7 // 子类会继承父类使用的注解中被@Inherited修饰的注解
     8 @Inherited
     9 // 当前是SpringBoot配置类
    10 @SpringBootConfiguration
    11 // 开启自动配置
    12 @EnableAutoConfiguration
    13 // 扫描当前注解类的包路径
    14 @ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
    15         @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
    16 public @interface SpringBootApplication {
    17 
    18     ......
    19 
    20 }

    @EnableAutoConfiguration注解如下:

      @EnableAutoConfiguration 包含了@AutoConfigurationPackage注解

     1 @Target(ElementType.TYPE)
     2 @Retention(RetentionPolicy.RUNTIME)
     3 @Documented
     4 @Inherited
     5 @AutoConfigurationPackage
     6 @Import(AutoConfigurationImportSelector.class)
     7 public @interface EnableAutoConfiguration {
     8 
     9     ......
    10 
    11 }
    1 @Target(ElementType.TYPE)
    2 @Retention(RetentionPolicy.RUNTIME)
    3 @Documented
    4 @Inherited
    5 @Import(AutoConfigurationPackages.Registrar.class)
    6 public @interface AutoConfigurationPackage {
    7 
    8 }

    二、自动配置原理图解

      

      说明:

      AutoConfigurationImportSelector.class

      1、Spring解析AutoConfigurationImportSelector.class 导入类的时候,会延迟解析,应为它实现了 DeferredImportSelector 延迟导入选择器接口

      2、AutoConfigurationImportSelector 导入类的时候,会从META-INF/spring.factories中获取 EnableAutoConfiguration 类型的类名称

      3、然后Spring在解析 EnableAutoConfiguration 类型的类,大部分都是一些自动配置类 XXXAutoConfiguration,Spring通过解析这些自动配置类就能得到需要导入类的Bean定义

      4、最后在通过Bean定义初始化成类对象,完成了自动配置功能

     

  • 相关阅读:
    source : not found 原因及解决办法
    hdfs 数据坏块导致datanode不能正常上报数据块
    hadoop 基准测试
    Linux yum 安装mysql的时候指定安装版本
    如何从头构建一个只有bash的镜像
    创建自己的基础镜像
    go学习(2)变量
    Go学习(1)go安装
    spark on yarn 错误
    mysqld: File './mysql-bin.index' not found (Errcode: 13
  • 原文地址:https://www.cnblogs.com/h--d/p/14797662.html
Copyright © 2011-2022 走看看