自动配置:
pom.xml
- spring-boot-dependencies 核心依赖在父工程中
- 我们在写或者引入springboot依赖的时候,不需要指定版本,就是因为有这些版本仓库
启动器
- 启动器:说白了就是springboot的一个启动场景
-
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency>
- 比如:spring-boot-starter-web,他就会帮我们导入web环境所有的依赖
- springboot会将所有的功能场景,都变成一个个的启动器
- 我们要使用什么功能,就只需要找到对应的启动器就可以了
stater
主程序
//@SpringBootApplication 标注这个类是一个springboot的应用
@SpringBootApplication
public class SpringbootplaybackApplication {
public static void main(String[] args) {
//将springboot应用启动
SpringApplication.run(SpringbootplaybackApplication.class, args);
}
}
- 注解
-
@SpringBootConfiguration //springboot的配置 @Configuration //spring配置类 @Component //说明这也是spring的一个组件 @EnableAutoConfiguration //自动配置 @AutoConfigurationPackage //自动配置包 @Import(AutoConfigurationPackages.Registrar.class) //自动配置`包注册` @Import(AutoConfigurationImportSelector.class) //获取所有的配置 List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);
- 获取候选的配置
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) { List<String> configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(), 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; }
- META-INF/spring.factories 自动配置的核心文件!
Properties properties = PropertiesLoaderUtils.loadProperties(resource);
所有的资源加载到配置类中 -
流程图
总结
springboot所有的自动配置都在启动类中被扫描并加载
spring.factories
,所有的自动配置都在这里面,但是不一定生效,要判断条件是否成立,要导入对应的start,就有对应的启动器了,有了启动器,自动装配就会生效,然后就配置成功!
- springboot在启动的时候,从类路径下META-INF/
spring.factories
获取指定的值 - 将这些自动配置的类倒入容器,自动配置类就会生效,帮我们进行自动配置
- 以前我们需要手动配置的东西,现在springboot帮我们做了
- 整个javaEE解决方案和自动配置的东西都在
spring-boot-autoconfigure-2.4.1.jar
这个包下 - 他会把所有需要导入的组件以类名的方式返回,这些组件就会被添加到容器;
- 容器中也会存在非常多的XXXXAutoConfiguration(@Bean)的文件,就是这些类给容器中导入了这个场景需要的所有组件,并自动配置,@Configuration,javaConfig
- 那有了自动配置类,免去了我们手动编写配置文件的工作!