SpringMVC是一个框架,它是Spring里的一个 WEB 模块;
而 SpringBoot 从严格意义上来讲是一个配置工具,整合工具。实现自动配置,从配置繁琐(xml
)到零配置 (yml
)
1 构建聚合工程
聚合工程 里可以分为 顶级项目(顶级工程、父工程)与 子工程,子工程在 maven 里称为 模块(module),模块之间是平级的,是可以相互依赖的。
子模块可以使用顶级工程里所有的资源(依赖),子模块之间如果要使用资源,必须构建依赖。
一个顶级工程是可以由多个不同的子工程构成
在 idea 中直接创建一个空白的 Maven 项目即可,在 顶级项目 的 pom
文件中需要声明 <packaging>
标签为 pom
。
鼠标右键 顶级项目 新增 Module
即可创建 子项目,创建之后在 顶级项目 的 pom
文件中会出自动生成 <Modules>
标签,它代表子模块集合(子项目 的默认打包方式为 jar
)。
子模块之间的依赖,使用
<dependencies>
标签。
2 整合 SpringBoot
2.1 引入依赖
在 顶级项目 的 pom
文件中引入父级依赖 :
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
<!-- <relativePath/>设定一个空值默认值为../pom.xml 表示将始终从父级仓库中获取,不从本地路径获取 -->
<relativePath />
</parent>
spring-boot-starter-parent
是 SpringBoot 的父级依赖,使用 idea 按着 ctrl
点击 pom
文件中 spring-boot-starter-parent
,可以查看到它还有一个父级依赖 spring-boot-dependencies
,再点击查看,这个 spring-boot-dependencies
默认加载了很多的依赖,起一个依赖管理作用。
即 spring-boot-starter-parent
实质是起一个 依赖版本管理 的作用
<parent>
标签表示:依赖对应标签项目所对应的jar包依赖,但不引入标签项目的 java文件等
<dependency>
标签表示:依赖标签项目所对应的所有内容,包括 jar包依赖,标签项目的 java文件等
声明了父级依赖之后,所需要使用的依赖还是要使用 <dependency>
进行注明:
<!--
这里的 dependency 无需定义 version,version 全部由 spring-boot-starter-parent 定义管理
-->
<dependencies>
<!-- 表明使用 Spring Boot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- Spring 容器的 web 模块 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- SpringBoot 配置解析默认只能解析yml文件,想要解析xml,properties 格式文件就需要使用这个依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
2.2 构建启动类
在引入完依赖之后,就需要创建启动类和配置文件。一般来说,启动类和总配置文件都放置在 Controller
模块中,由于启动类的 @SpringBootApplication
注解默认会扫描当前包下的所有的类,所以一般会把该文件放置到基础包上如 top.seiei
中。
/**
* 这个类用于启动项目的,@SpringBootApplication 注解表示
* 点击 @SpringBootApplication 注释查看
* 其中 @ComponentScan 这个注释表示扫描类的,Application 类声明在 top.seiei 中,他就会默认扫描当前包(即 top.seiei 包内)及子包下所有的类
* 其中 @SpringBootConfiguration 则表示它是一个 bean 容器
* 其中 @EnableAutoConfiguration 则表示自动装配备用的、默认的配置(tomcat、springMVC 之类的配置),帮我们自动装配(为什么使用SpringBoot就可以做到几乎零配置)
*/
@SpringBootApplication
/**
* 扫描所有包,以及相关组件包
* 不添加 @ComponentScan 注释,就只会默认扫描 top.seiei 包
*/
@ComponentScan(basePackages = {"top.seiei", "org.n3r.idworker"})
/**
* 扫描 mapper
*/
@MapperScan(basePackages = "top.seiei.mapper")
public class Application {
public static void main(String[] args) {
// 使用 SpringApplication 中的 run 方法,它是一个静态的助手类方法,它用于执行一个 SpringApplication 实例
SpringApplication.run(Application.class, args);
}
}
此时无需额外配置 yml
文件就可以运行启动类了,相对于直接使用 SpringMVC 的,很多的刚需配置文件都被忽略掉了,这都是得益于 SpringBoot 的自动装配,点击 @SpringBootApplication
注解中查看,具体可看上面代码的注释。