自动配置
pom.xml
- spring-boot-dependencies : 核心依赖在父工程中
- 写或者引入一些SpringBoot依赖的时候,不需要指定版本,是因为有这些版本仓库
启动器
-
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> -
启动器:本质就是SpringBoot的启动场景;
- 如spring-boot-starter-web 就会自动导入web环境所有的依赖!
- SpringBoot会将所有的功能场景 都变成一个个启动器; 如果要使用功能,只需要引入最新的依赖就可以了;
主程序
-
// @SpringBootApplication: 标注这个类是一个springboot的应用,启动类下所有的资源被导入 @SpringBootApplication @MapperScan("cn.springSecurity.dao") // 扫描包路径 public class SpringSecurityDemoApplication { public static void main(String[] args) { // springboot 启动类 SpringApplication.run(SpringSecurityDemoApplication.class, args); } } - 注解
@SpringBootConfiguration : springboot的配置
@Configuration : spring配置类
@Component : 说明也是spring组件
@EnableAutoConfiguration : 自动配置
@AutoConfigurationPackage : 自动配置包
@Import({AutoConfigurationPackages.Registrar.class}): 导入选择器 包注册
@Import({AutoConfigurationImportSelector.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.loadProperties(resource);
导图梳理
理论(谈资)
实现自动装配主要依靠三个核心技术,分别是:
1、引入Starter,启动依赖组件的时候,这个组件里面必须要包含一个@Configuration配置类,在这个配置类里面我们需要通过@Bean这个注解声明需要装配到IOC容器里面的Bean对象;
2,扫描第三方jar包的配置类,这个步骤主要是用到了Spring里面的SpringFactoriesLoader来完成的;
3、实现配置类的动态加载,SpringBoot拿到所有第三方jar包里面声明的配置类以后,再通过Spring提供的importSelector接口来实现这些配置类的动态加载,从而去完成自动装配的动作。