一、自动配置
自动配置的核心文件
pom.xml中
<!-- 有一个父项目-->
<parent>
<artifactId>spring-boot-starter-parent</artifactId>
<groupId>org.springframework.boot</groupId>
<version>2.4.1</version>
</parent>
所以我们再写依赖时候,可以省去版本号
二、启动器
启动器说白了就是spring boot的启动场景。我们需要那个启动器,添加依赖,就会帮我们导入所有的配置。需要哪个启动器,就添加那个启动器依赖(‘start’)
springBoot各种启动器网址
<!--默认启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!--web启动器,web依赖:tomcat,dispatcherServlet.xml-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--单元测试启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
主程序
@SpringBootApplication
标注当前类是一个spring boot的应用。没有就会报错
@SpringBootApplication下的核心
1、@SpringBootConfiguration
spring boot的配置
@Configuration
@SpringBootConfiguration下的配置。也是spring的配置
@Component
@Configuration下的说明是一个一个组件
2、@EnableAutoConfiguration
自动配置
1)、@AutoConfigurationPackage
自动配置包。@EnableAutoConfiguration下
@Import({Registrar.class})
@AutoConfigurationPackage下的。自动配置包注册
2)、@Import({AutoConfigurationImportSelector.class})
自动配置导入选择
AutoConfigurationImportSelector类下的方法
//获取所有的配置
List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes);
获取候选的配置。getCandidateConfigurations(annotationMetadata, attributes)方法下的方法
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
List<String> 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;
}
SpringApplication.run(。。。)
将spring boot应用启动
public static void main(String[] args) {
SpringApplication.run(SpringbootZzcApplication.class, args);
}
结论
spring boot所有自动配置都是在启动的时候扫描兵=并加载:spring.factories所有的自动配置类都在这里面,但是不一定生效,要判断条件是否成立,只要导入对象的start。就有对应的启动器,有了启动器自动装配就会生效。配置成功