SpringBoot自动装配原理
1. 父工程管理了核心依赖
springboot 的父工程spring-boot-dependencies中已经管理了大量核心依赖的相关版本信息,当我们在引入springboot依赖时,不需要指定版本(springboot能识别的)。
<!-- pom.xml -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.10</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<!-- spring-boot-starter-parent-xxx.xml-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.5.10</version>
</parent>
<!-- spring-boot-dependencies-xxx.xml-->
<!-- 此文件中管理了大量的springboot核心依赖及其相应的版本 -->
2. SpringBoot启动器
以spring-boot-starter-web为例
<!-- pom.xml -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
- 启动器就是springboot的启动场景
- 比如引入spring-boot-starter-web,它就会从核心依赖中帮我们自动导入web相关的所有依赖
- springboot将所有的功能场景,变成一个一个的启动器
- 需要什么功能,只需要找到对应的启动器
starter详情参考官网
3. 启动类及自动配置基本原理
@SpringBootApplication 标注这个类是一个springboot应用,自动配置原理基于此注解。
- springboot启动是会从spring-boot-autoconfigure-2.5.10.jar下的META-INF\spring.factories中读取允许自动配置一下信息
- springboot根据一些条,如一些class文件是否存在或者一些属性配置是否存在等条件,判断是否可以自动配置
- 条件满足将自动配置
详情见流程图