SpringBoot自动配置

  1. @SpringBootApplication
    作用:标注在某个类上说明这个类是SpringBoot的主配置类 , SpringBoot就应该运行这个类的main方法来启动SpringBoot应用
    点进去@SpringBootApplication:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
		@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
}
  1. @ComponentScan
    作用:自动扫描并加载符合条件的组件或者bean , 将这个bean定义加载到IOC容器中(它对应XML配置中的元素)

  2. @SpringBootConfiguration
    作用:SpringBoot的配置类 ,标注在某个类上 , 表示这是一个SpringBoot的配置类;

点进去@SpringBootConfiguration :

@Configuration
public @interface SpringBootConfiguration {}

@Component
public @interface Configuration {}

@Configuration,说明这是一个配置类 ,配置类就是对应Spring的xml 配置文件
@Component 这就说明,启动类本身也是Spring中的一个组件,负责启动应用

  1. @EnableAutoConfiguration
    @EnableAutoConfiguration告诉SpringBoot开启自动配置功能,这样自动配置才能生效
    点进注解:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
}
  1. @AutoConfigurationPackage :自动配置包

@Import({Registrar.class})
public @interface AutoConfigurationPackage {
}
  1. @import :Spring底层注解@import , 给容器中导入一个组件

Registrar.class 作用:将主启动类的所在包及包下面所有子包里面的所有组件扫描到Spring容器

  1. @Import({AutoConfigurationImportSelector.class}) :给容器导入组件
    AutoConfigurationImportSelector :自动配置导入选择器

spring.factories:内含自动配置文件

自动配置原理:从classpath中搜寻所有的META-INF/spring.factories配置文件 ,并将其中对应的 org.springframework.boot.autoconfigure 包下的配置项,通过反射实例化为对应标注了 @Configuration的JavaConfig形式的IOC容器配置类 , 然后将这些都汇总成为一个实例并加载到IOC容器中

流程图:
1.在spring.factories中找到需要的自动配置类在这里插入图片描述
2.自动配置类从properties类获得属性
在这里插入图片描述
@EnableConfigurationProperties({XXXProperties.class})
@EnableAutoConfiguration启动指定类的ConfigurationProperties功能:

  1. 进入这个XXXProperties查看,将配置文件中对应的值和XXXProperties绑定起来
  2. 并把XXXProperties加入到ioc容器中在这里插入图片描述
    yaml中赋值
    在这里插入图片描述

总结:
1.SpringBoot在启动的时候从类路径下的META-INF/spring.factories中获取EnableAutoConfiguration指定的值,并将这些值作为自动配置类导入容器,进行自动配置工作
2.(1)SpringBoot启动会加载大量的自动配置类

(2)我们看我们需要的功能有没有在SpringBoot默认写好的自动配置类当中;

(3) 我们再来看这个自动配置类中到底配置了哪些组件;(只要我们要用的组件存在在其中,我们就不需要再手动配置了)

(4)给容器中自动配置类添加组件的时候,会从properties类中获取某些属性。我们只需要在配置文件中指定这些属性的值即可

注:xxxxAutoConfigurartion:自动配置类;给容器中添加组件

xxxxProperties:封装配置文件中相关属性;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

hvk_l

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

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

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

打赏作者

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

抵扣说明:

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

余额充值