前言

前面我们花了很多篇幅学习 Spring、SpringMVC、MyBatis,每次搭建项目都要写一堆配置类、导入各种坐标,虽然功能强大,但确实繁琐。今天终于迎来了“简化大师”——SpringBoot

SpringBoot 的设计目标就是简化 Spring 应用的初始搭建和开发过程。学完今天的内容,你会发现以前那些繁琐的配置文件、依赖坐标都可以精简到一个文件甚至一个注解搞定。

💬 课前唠一唠:你还记得第一次搭 SSM 项目时写了多少个配置文件吗?SpringConfigSpringMvcConfigServletConfigJdbcConfigMybatisConfig……在评论区说说你被哪些配置文件折磨过,看看谁列的清单最长!


一、SpringBoot 简介

1.1 回顾 SpringMVC 开发的繁琐

以 SpringMVC 开发为例,一个项目要跑起来需要做多少事?

  1. 创建工程,在 pom.xml 中手动添加 spring-webmvcjavax.servlet-api 等依赖
  2. 编写 Web 3.0 配置类AbstractAnnotationConfigDispatcherServletInitializer
  3. 编写 SpringMVC 配置类@Configuration + @ComponentScan + @EnableWebMvc
  4. 编写 Controller 类

前三步基本上是每个项目的“固定动作”,却占用了大量时间。SpringBoot 就是为了消除这些固定动作而生的。

1.2 SpringBoot vs Spring 对比

对比项 Spring 程序 SpringBoot 程序
pom.xml 坐标 手动添加,版本号自己管理 勾选技术,自动生成
Web 3.0 配置类 需要自己写 不需要
Spring/SpringMVC 配置类 需要自己写 不需要
Controller 需要自己写 需要自己写

前三项全部简化掉了,开发者只需要关注业务逻辑(Controller)即可。


二、SpringBoot 快速入门

2.1 三步跑起来

步骤 1:创建 SpringBoot 工程

在 IDEA 中选择 Spring Initializr(快速构建 SpringBoot 工程的方式),配置基本信息:

  • 打包方式:Jar(不是 War!)
  • 勾选技术:Spring Web(会自动导入 spring-webmvc 等依赖)

生成后可以删掉无用的文件:.mvn.gitignoreHELP.mdmvnwmvnw.cmd

步骤 2:编写 Controller

@RestController
@RequestMapping("/books")
public class BookController {
    
    @GetMapping("/{id}")
    public String getById(@PathVariable Integer id) {
        System.out.println("id == " + id);
        return "hello, spring boot!";
    }
}

步骤 3:运行 Application 类的 main 方法

不需要本地 Tomcat,不需要 Tomcat 插件,SpringBoot 内置了服务器,直接运行即可。

访问 http://localhost:8080/books/1,看到 "hello, spring boot!" 就成功了。

2.2 为什么这么简单?

看两个关键文件:

Application 引导类

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

@SpringBootApplication 是一个组合注解,包含了 @SpringBootConfiguration@EnableAutoConfiguration@ComponentScan,一个注解搞定一切。

pom.xml

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.5.0</version>
</parent>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
  • spring-boot-starter-parent:父工程,管理了所有依赖的版本号,你导入依赖时不需要写版本
  • spring-boot-starter-web:起步依赖,它里面又依赖了 spring-webmvcspring-boot-starter-tomcat 等,一个依赖打包了所有 web 开发需要的 jar 包

💡 核心思想

  • 起步依赖(starter):解决依赖设置繁琐的问题,一个 starter 包含该技术需要的所有坐标
  • 自动配置:解决配置繁琐的问题,SpringBoot 自动配置好常用的 bean
  • 内置服务器:不需要外部 Tomcat,jar 包自带运行环境

三、配置文件

3.1 三种配置文件格式

SpringBoot 的配置文件名必须是 application,支持三种后缀:

格式 文件名 示例
properties application.properties server.port=80
yml application.yml server: \n port: 81
yaml application.yaml 同 yml

优先级properties > yml > yaml

3.2 yaml 语法规则

YAML 格式更直观,是现在的主流选择。核心规则:

  • 大小写敏感
  • 属性层级用缩进表示(只能用空格,不能用 Tab)
  • 属性名与值之间用 冒号 + 空格 分隔
  • # 表示注释

普通数据

enterprise:
  name: itcast
  age: 16
  tel: 4006184000

数组数据:用 - 开头

subject:
  - Java
  - 前端
  - 大数据

📝 记住这句核心规则:数据前面要加空格与冒号隔开。

3.3 读取配置数据的三种方式

方式一:@Value 注解
@Value("${lesson}")
private String lesson;

@Value("${server.port}")
private Integer port;

@Value("${enterprise.subject[0]}")
private String subject_00;

适合读取少量零散的配置值。

方式二:Environment 对象
@Autowired
private Environment env;

public void test() {
    System.out.println(env.getProperty("lesson"));
    System.out.println(env.getProperty("enterprise.name"));
}

框架内置了大量数据,适合一次性读取多个不相关的配置。

方式三:自定义对象(最优雅)
@Component
@ConfigurationProperties(prefix = "enterprise")
public class Enterprise {
    private String name;
    private int age;
    private String tel;
    private String[] subject;
    // getter/setter/toString 略
}

直接注入使用:

@Autowired
private Enterprise enterprise;

⚠️ 如果实体类上有黄色波浪线警告,在 pom.xml 中添加以下依赖即可:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

🎯 实战推荐:少量配置用 @Value,一组相关配置用 @ConfigurationProperties 绑定到实体类,最清晰最优雅。

3.4 多环境配置

开发、测试、生产环境的配置肯定不一样。SpringBoot 提供了便捷的多环境切换方案。

yaml 方式(用 --- 分割不同环境):

# 指定使用哪个环境
spring:
  profiles:
    active: dev

---
# 开发环境
spring:
  config:
    activate:
      on-profile: dev
server:
  port: 80

---
# 生产环境
spring:
  config:
    activate:
      on-profile: pro
server:
  port: 81

---
# 测试环境
spring:
  config:
    activate:
      on-profile: test
server:
  port: 82

properties 方式:创建多个配置文件

  • application-dev.properties(开发)
  • application-pro.properties(生产)
  • application-test.properties(测试)

application.properties 中指定:

spring.profiles.active=pro

命令行切换(打包后临时指定):

java -jar xxx.jar --spring.profiles.active=test
java -jar xxx.jar --server.port=88 --spring.profiles.active=test

命令行参数优先级最高

3.5 配置文件优先级(4级)

级别 位置 优先级
1级 classpath:application.yml 最低
2级 classpath:config/application.yml
3级 file:application.yml(jar 包同目录)
4级 file:config/application.yml 最高

级别越高,优先级越高。打包后如果测试人员需要临时改配置,可以在 jar 包同级的 config/ 目录下放一份配置文件。


四、SpringBoot 整合 Junit

回顾原生 Spring 整合 Junit 需要写 @RunWith + @ContextConfiguration。SpringBoot 只要一个注解:

@SpringBootTest
class Springboot07TestApplicationTests {
    
    @Autowired
    private BookService bookService;
    
    @Test
    public void save() {
        bookService.save();
    }
}

⚠️ 注意事项:测试类所在的包必须是引导类所在包或其子包。如果不在同一个包下,需要手动指定:

@SpringBootTest(classes = Springboot07TestApplication.class)

五、SpringBoot 整合 MyBatis

5.1 与原生 Spring 整合的对比

原生 Spring 整合 MyBatis 需要

  • JdbcConfig 配置类(数据源、driver、url、username、password)
  • MybatisConfig 配置类(SqlSessionFactoryBean、MapperScannerConfigurer)
  • SpringConfig 引入以上两个配置类

SpringBoot 整合 MyBatis 只需要

  1. 创建工程时勾选 MyBatis 和 MySQL
  2. application.yml 中配置数据源
  3. Dao 接口上加 @Mapper 注解

5.2 具体步骤

步骤 1:创建工程时勾选 MyBatis、MySQL

步骤 2:定义实体类和 Dao 接口

public class Book {
    private Integer id;
    private String name;
    private String type;
    private String description;
    // getter/setter/toString 略
}

@Mapper
public interface BookDao {
    @Select("select * from tbl_book where id = #{id}")
    Book getById(Integer id);
}

步骤 3:配置数据源(application.yml)

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/ssm_db?serverTimezone=UTC
    username: root
    password: root
    type: com.alibaba.druid.pool.DruidDataSource

步骤 4:测试

@SpringBootTest
class Springboot08MybatisApplicationTests {
    @Autowired
    private BookDao bookDao;
    
    @Test
    void testGetById() {
        Book book = bookDao.getById(1);
        System.out.println(book);
    }
}

常见问题

  • MySQL 驱动类名:老版本用 com.mysql.jdbc.Driver,新版本用 com.mysql.cj.jdbc.Driver
  • 时区问题:url 后面加 ?serverTimezone=UTC
  • 默认数据源是 HikariCP,想用 Druid 需要手动导入依赖并在配置中指定 type

六、SSM 整合案例(SpringBoot 版)

用 SpringBoot 把之前 SSM 整合的案例重做一遍,你会发现工作量大大减少。

操作 原生 SSM SpringBoot
pom.xml 依赖 手动写一堆坐标 勾选 Web、MySQL、MyBatis
配置类(Spring/MVC) 需要自己写 全部删除
JdbcConfig 需要自己写 全部删除
MybatisConfig 需要自己写 全部删除
Dao 接口 需要包扫描或配置文件 @Mapper 注解即可
静态资源 放在 webapp 目录下 放在 resources/static
数据源 yml 配置(可指定 druid) yml 配置(可指定 druid)

配置文件示例

server:
  port: 80

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/ssm_db
    username: root
    password: root

只需要这一个配置文件 + @Mapper 注解,SSM 整合就完成了!


七、总结

今天我们学习了 SpringBoot 如何简化 Spring 开发:

模块 核心知识点
SpringBoot 定位 简化 Spring 应用的搭建和开发
两个核心机制 起步依赖(简依赖)、自动配置(简配置)
引导类 @SpringBootApplication + SpringApplication.run()
配置文件 properties/yml/yaml 三种格式,优先级 properties > yml > yaml
数据读取 @ValueEnvironment@ConfigurationProperties
多环境配置 spring.profiles.active 切换,命令行 -- 参数优先级最高
整合 Junit @SpringBootTest 一个注解搞定
整合 MyBatis 勾选技术 + yml 数据源配置 + @Mapper 注解
静态资源 放在 resources/static 目录下

🎤 结课小调查:学完 SpringBoot,你觉得最让你“相见恨晚”的功能是哪个?
A. 不用写配置类了
B. 起步依赖,一个 starter 搞定所有坐标
C. yaml 配置文件,比 properties 清晰太多
D. @ConfigurationProperties 一键绑定配置到实体类

评论区告诉我你的选择!如果你已经跟着教程跑通了 SSM 整合,欢迎截图晒出你的项目结构和运行结果。


本文为 SpringBoot 第一天授课内容整理。SpringBoot 让开发回归简洁,后面的微服务和分布式开发都建立在它之上。如果觉得有帮助,欢迎点赞、收藏、关注,我们下节课见!

更多推荐