抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

摘要:本文学习了Spring Boot能够快速创建项目的原理。

环境

Windows 10 企业版 LTSC 21H2
Java 1.8
Maven 3.6.3
Spring 5.3.31
Spring Boot 2.7.18

1 依赖版本

1.1 仲裁中心

查看项目的pom.xml文件,找到父依赖:

pom.xml
1
2
3
4
5
6
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.18</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

继续查看spring-boot-starter-parent父项目的pom.xml文件,找到依赖的父项目:

pom.xml
1
2
3
4
5
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.7.18</version>
</parent>

继续查看spring-boot-dependencies父项目的pom.xml文件,找到定义的版本:

pom.xml
1
2
3
<properties>
...
</properties>

因为在spring-boot-dependencies项目中定义了版本,所以将这个项目称为版本仲裁中心。

1.2 组合依赖

查看项目的pom.xml文件,找到项目依赖:

pom.xml
1
2
3
4
5
<!-- Spring Boot Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

查看spring-boot-starter-web项目的pom.xml文件,发现包含了使用Web需要的依赖,这些依赖同样使用版本仲裁中心定义的版本。

Spring Boot提供了不同的Starter项目,一个典型的Starter项目包含两部分:

  • 依赖管理:声明实现功能所需要的依赖版本,并且通过版本仲裁中心统一管理。
  • 自动配置:根据项目依赖自动配置应用程序的行为。

2 核心注解

使用@SpringBootApplication注解标识启动类,该注解也被称为核心注解:

java
1
2
3
4
5
6
7
8
9
10
11
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
@Filter(type = FilterType.CUSTOM, classes = {TypeExcludeFilter.class}),
@Filter(type = FilterType.CUSTOM, classes = {AutoConfigurationExcludeFilter.class})
})
public @interface SpringBootApplication {

核心注解包含了三个注解:

  • 使用@SpringBootConfiguration注解可以标记启动类为配置类,类似于@Configuration注解。
  • 使用@EnableAutoConfiguration注解可以开启自动配置,按需导入AutoConfiguration结尾的配置类。
  • 使用@ComponentScan注解可以启用组件扫描,默认会扫描启动类所在的包及其子包,自动注册为Spring容器对象。

评论