首页 > 技术文章 > SpringBoot 自动配置原理

huang580256 2021-04-04 16:06 原文

1,原理初探

pom.xml

  • spring-boot-dependencies:核心依赖在父工程中!
  • 我们在写或者引入一些springboot依赖的时候,不需要指定版本,因为有这些版本仓库

2,启动器

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter</artifactId>
</dependency>
  • 启动器:就是springboot的启动场景

  • 比如:spring-boot-starter-web他会自动帮我们导入web环境的所有依赖!

  • springboot会将所有的功能场景,变成一个个的启动器

  • 我们要使用什么功能,只需找到对应的启动器就行,starter

3,主程序

@SpringBootApplication
public class HelloApplication {
	public static void main(String[] args) {
		SpringApplication.run(HelloApplication.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:自动配置的核心文件

image

 Properties properties = PropertiesLoaderUtils.loadProperties(resource);
 所有的资源加载到配置类中

image

结论:springboot所有的自动配置都是在启动的时候扫描并加载:spring.factories所有的自动配置类都在这里面,但是不一定生效,要判断条件是否成立,只要导入了对应的start,就有对应的启动器,有了启动器,自动装配就会生效,然后就配置成功了!

推荐阅读