Spring Boot的自动配置
时间:2021-06-02 17:50:55
收藏:0
阅读:0
Spring Boot的特点
1.依赖管理
父项目做依赖管理
<!-- HelloWorld项目的父项目 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.11.RELEASE</version>
</parent>
<!-- 父项目的父项目 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.3.11.RELEASE</version>
</parent>
spring-boot-dependencies中几乎声明了所有我们开发时要用到依赖的版本号,今后我们用到它管理的依赖可以不用写版本号,由这个父项目自动仲裁版本号。
2.场景启动器starter
- Spring Boot为我们提供了很多场景启动器:spring-boot-starter-,表示是某种场景,如spring-boot-starter-web。
- 只要在pom文件中引入了某种starter,那么这个场景需要的一些常规的依赖Spring Boot都会自动帮我们引入。
- Spring Boot支持的所有场景启动器 Spring Boot支持的starters
- *-spring-boot-starter:第三方为我们提供的场景启动器
- 各场景启动器用到的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>2.3.4.RELEASE</version>
<scope>compile</scope>
</dependency>
-
引入依赖时无需指定版本号,有spring-boot-dependencies自动仲裁
-
引入非spring-boot-dependencies管理的依赖,需要指明版本号
-
可以修改自动仲裁的版本号
<!-- 在当前项目里重新配置,key要与spring-boot-dependencies保持一致 -->
<properties>
<mysql.version>5.3.33</mysql.version>
<properties>
3.自动配置
-
自动配好Tomcat
- 引入了Tomcat依赖
- 配置了Tomcat
-
自动帮我们配置好了Spring MVC
- 自动引入了Spring MVC的全套组件
- 自动配置好了Spring MVC的常用组件
-
自动配置好了web常见的功能组件,如字符集过滤器
Spring Boot在我们引入的场景下为我们自动装配很多功能组件 -
Spring Boot项目默认的包结构
- Spring Boot默认的包扫描规则:主程序类所在的包以及该包下面的所有子包下的所有组件都会被默认地扫描进容器
- 无需向以前在Spring中那样需要指定扫描路径
- 可以改变包扫描路径
//这样指定 @SpringBootApplication(scanBasePackages = {"boot"}) //也可以这样指定 //@SpringBootApplication(scanBasePackages = {"boot"}) @SpringBootConfiguration @EnableAutoConfiguration @ComponentScan(basePackages={"boot"}) public class MainApplication { public static void main(String[] args) { SpringApplication.run(MainApplication.class, args); } }
-
Spring Boot默认配置的各个组件都有默认的配置值
- 在配置文件中的配置项都会映射到某个具体的类,如:ServerProperties
- 配置文件的值最终会绑定到每个类上,这个类会在容器中创建兑象
-
Spring Boot按需加载需要的配置项
- Spring Boot有这非常多的starter,在引入了指定的starter后,这个场景的自动配置才会开启生效
- Spring Boot的所有自动配置功能都在spring-boot-autoconfigure下
-
未完待续...
评论(0)