系列:后端路线 · Part 2
上一篇(MySQL)让你会存数据。这一篇让你会”写程序去操作数据”。Spring Boot 是 Java 后端事实标准框架,目标:能搭起一个项目、写出接收 HTTP 请求并读写 MySQL 的接口。

1. 为什么是 Spring Boot?

Spring 是庞大的 Java 企业级框架,但”原生 Spring”配置繁琐。Spring Boot 的核心思想是”约定优于配置 + 自动装配”

  • 内嵌 Tomcat,无需单独部署 Web 容器,java -jar 直接跑。
  • starter 依赖一键引入常用能力(web、mysql、mybatis…)。
  • 自动根据 classpath 配置好 Bean,几乎零 XML。

面试常问:”Spring 和 Spring Boot 区别?” 答:Spring Boot 是基于 Spring 的快速开发脚手架,通过自动配置和起步依赖极大简化了搭建与配置。

2. 项目结构(标准分层)

1
2
3
4
5
6
7
8
9
10
11
12
13
src/main/java/com/example/demo/
├── DemoApplication.java ← 启动类(@SpringBootApplication)
├── controller/ ← 接收 HTTP 请求,调 Service
│ └── UserController.java
├── service/ ← 业务逻辑
│ └── UserService.java
├── mapper/ 或 dao/ ← 数据库访问(MyBatis / JPA)
│ └── UserMapper.java
└── entity/ 或 domain/ ← 数据实体(对应数据库表)
└── User.java
resources/
├── application.yml ← 配置文件(端口、数据库连接等)
└── static/ / templates/ ← 前端资源(可选)

分层口诀:Controller 接活 → Service 干活 → Mapper 存取 → Entity 搬运数据。

3. 启动类与核心注解

1
2
3
4
5
6
@SpringBootApplication   // = @Configuration + @EnableAutoConfiguration + @ComponentScan
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}

常用 Web 注解:

注解 作用
@RestController 标记类为接口层,返回 JSON(= @Controller + @ResponseBody
@RequestMapping("/api/user") 类/方法级路由前缀
@GetMapping / @PostMapping / @PutMapping / @DeleteMapping 对应 HTTP 方法
@PathVariable("id") 取路径参数 /api/user/{id}
@RequestParam 取 URL 查询参数 ?name=xxx
@RequestBody 取请求体 JSON 并反序列化为对象

4. 依赖注入(IoC)

Spring 容器管理对象(Bean),你只声明”我需要什么”,容器自动注入:

1
2
3
4
5
6
7
8
@Service              // 标记为业务 Bean
public class UserService {
@Autowired // 注入 Mapper
private UserMapper userMapper;
// 或构造器注入(推荐,更利于测试)
// private final UserMapper userMapper;
// public UserService(UserMapper m){ this.userMapper = m; }
}

面试点:IoC(控制反转) 是把对象创建权交给容器;DI(依赖注入) 是容器把依赖塞进来。二者一体两面。

5. 连接 MySQL(application.yml)

1
2
3
4
5
6
7
8
server:
port: 8080
spring:
datasource:
url: jdbc:mysql://localhost:3306/demo_db?useUnicode=true&characterEncoding=utf8mb4&serverTimezone=Asia/Shanghai
username: root
password: your_password
driver-class-name: com.mysql.cj.jdbc.Driver

注意 characterEncoding=utf8mb4serverTimezone,少了常踩时区/乱码坑(详见”常见问题”篇)。

6. 实操:一个 CRUD 接口(MyBatis-Plus 版)

Entity

1
2
3
4
5
6
7
8
9
@TableName("user")
public class User {
@TableId(type = IdType.AUTO)
private Long id;
private String username;
private Integer age;
private BigDecimal balance;
// getter/setter 省略
}

Mapper(继承 BaseMapper 即获得 CRUD,无需写 SQL)

1
2
@Mapper
public interface UserMapper extends BaseMapper<User> {}

Service

1
2
3
4
5
6
7
8
9
10
@Service
public class UserService extends ServiceImpl<UserMapper, User> {
public User create(String username, int age) {
User u = new User();
u.setUsername(username);
u.setAge(age);
this.save(u); // 来自 BaseMapper/IService
return u;
}
}

Controller

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
@RestController
@RequestMapping("/api/user")
public class UserController {
@Autowired
private UserService userService;

@PostMapping
public User create(@RequestBody User dto) {
return userService.create(dto.getUsername(), dto.getAge());
}

@GetMapping("/{id}")
public User get(@PathVariable Long id) {
return userService.getById(id);
}

@GetMapping
public List<User> list() {
return userService.list();
}

@PutMapping("/{id}")
public boolean update(@PathVariable Long id, @RequestBody User dto) {
dto.setId(id);
return userService.updateById(dto);
}

@DeleteMapping("/{id}")
public boolean delete(@PathVariable Long id) {
return userService.removeById(id);
}
}

这样 5 个接口就齐了:增(POST)、查列表(GET)、查单个(GET /{id})、改(PUT)、删(DELETE)——标准 RESTful 风格。

7. 启动与验证

1
2
mvn spring-boot:run          # 或 IDE 里直接跑 DemoApplication
curl http://localhost:8080/api/user

能返回 [] 或数据,说明链路打通:HTTP → Controller → Service → Mapper → MySQL。

8. 面试速通题

Q1:@Controller 和 @RestController 区别?
@RestController = @Controller + @ResponseBody,方法返回值直接写进响应体(JSON);@Controller 默认返回视图名(页面),需配合 @ResponseBody 才返回数据。

Q2:Spring Boot 怎么实现自动配置?
启动类的 @EnableAutoConfiguration 借助 spring.factories / AutoConfiguration.imports,按 classpath 存在的依赖自动装配对应 Bean(如检测到 MySQL 驱动就配 DataSource)。

Q3:Bean 的作用域有哪些?
singleton(默认,单例)、prototype(每次 new 一个)、request、session、application 等。

Q4:构造器注入和 @Autowired 字段注入,推荐哪个?
推荐构造器注入:不可变(final)、便于单元测试、避免 NPE、循环依赖更早暴露。

Q5:MyBatis 和 JPA 怎么选?
JPA/Spring Data 上手快、少写 SQL,适合简单 CRUD;MyBatis 灵活、SQL 可控、便于优化复杂查询,是国内大厂主流。MyBatis-Plus 兼顾两者(内置 CRUD + 可写 XML)。

下一篇:Part 3 API 与 HTTP 协议——把”接口”这件事从协议层讲清楚,否则你写的 @GetMapping 只是知其然。