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