一、核心注解
@SpringBootApplication:组合注解,包括以下注解。
- @SpringBootConfiguration:
配置注解,底层其实也是@Configuration注解,只不过在SpringBoot工程中更推荐使用@SpringBootConfiguration来替代Configuration。
- @EnableAutoConfiguration:
启动自动配置,根据所依赖的Jar包自动配置相关配置项。(后续会继续解释)
- @ComponentScan:
扫描配置,SpringBoot默认会扫描启动类所在的同级包及其子包。
二、基本配置
(1)问:这里只讲一点,假如不需要SpringBoot自动配置,想关闭某一项自动配置,又该如何设置?
(2)比如:此时你需要做一个短信验证码发送的微服务,但因为项目架构,不得已自动配置了数据源,此时需要去进行取消。
(3)解决:使用主动类上@SpringBootApplication下的exclude参数进行关闭。
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)//取消数据源自动配置
@SpringBootApplication(exclude = RedisAutoConfiguration.class)//取消redis自动配置
三、自动配置原理
(1)SpringBoot在SpringApplication对象实例化时会加载META-INF/spring.factories文件,将该配置文件载入Spring容器中,进行自动配置。
(2) getSpringFactoriesInstances->loadFactoryNames->加载了META-INF/spring.factories。
(3)关于spring.factores:用来指导SpringBoot找到指定的配置文件。
总结:Springboot是通过SpringFactoriesLoader的loadFactoryNames方法读取spring.factories文件的。而SpringFactoryLoader是Spring框架的一个工具类,主要功能是从META-INF/spring.factories加载配置。
@SpringBootApplication注解使用@EnableAutoConfiguration进行自动配置:从classpath路径下搜寻所有的META-INF/spring.factories配置文件,然后将其中对应的配置项通过反射实例化为对应的标注了@Configration的IoC容器配置类,最后汇总并加载到Spring框架的IoC容器中。