本专题导航
| 篇 | 主题 |
|---|---|
| 上一篇 | 自动配置与 Starter |
| 本篇 | Web、运维与测试 |
| 入门与启动 | |
| 配置与多环境 |
背景与动机
应用跑起来之后,日常开发会接触 REST 接口、统一异常、健康检查与集成测试。本篇覆盖 Web 层与运维向能力,并简要说明 MyBatis 整合入口(数据层细节可结合 MySQL 基础、Redis 基础)。
核心原理拆解
1. Web 请求映射注解
在 @RestController / @Controller 上使用:
| 注解 | HTTP |
|---|---|
@GetMapping | GET |
@PostMapping | POST |
@PutMapping | PUT |
@DeleteMapping | DELETE |
@PatchMapping | PATCH |
@RestController@RequestMapping("/api/users")public class UserController { @GetMapping("/{id}") public User get(@PathVariable Long id) { return userService.findById(id); }}2. 全局异常处理
@RestControllerAdvicepublic class GlobalExceptionHandler { @ExceptionHandler(BusinessException.class) public ResponseEntity<?> handle(BusinessException e) { return ResponseEntity.badRequest().body(e.getMessage()); }
@ExceptionHandler(Exception.class) public ResponseEntity<?> handleOther(Exception e) { return ResponseEntity.internalServerError().body("系统繁忙"); }}@RestControllerAdvice = @ControllerAdvice + @ResponseBody。更多异常体系见 Java 异常处理。
3. Actuator 监控
引入 spring-boot-starter-actuator,默认暴露部分端点(Boot 2.x+ 多在 /actuator 下):
| 端点 | 说明 |
|---|---|
/actuator/health | 健康检查 |
/actuator/beans | Bean 装配报告 |
/actuator/info | 应用信息 |
/actuator/shutdown | 关闭应用(默认关闭) |
生产环境通过 management.endpoints.web.exposure.include 控制暴露范围,并加认证。
4. 集成测试
@SpringBootTestclass UserServiceTest { @Autowired private UserService userService;
@Test void contextLoads() { assertNotNull(userService); }}切片测试(只加载 Web 层或 JPA 层):
@WebMvcTest:MockMvc 测 Controller@DataJpaTest:只测 Repository
5. 集成 MyBatis(入门)
依赖 mybatis-spring-boot-starter,配置示例:
spring: datasource: url: jdbc:mysql://localhost:3306/demo username: root password: secretmybatis: mapper-locations: classpath:mapper/*.xml type-aliases-package: com.example.entityMapper 接口加 @Mapper 或在启动类 @MapperScan("com.example.mapper")。
常见陷阱与错误示例
1. 生产环境误开 /actuator/shutdown
会被远程关闭应用,务必限制暴露端点并加安全认证。
2. 全局异常捕获过宽
@ExceptionHandler(Exception.class) 吞掉所有错误却不打日志,排查困难;至少记录堆栈,对外返回统一错误码。
3. @SpringBootTest 拉起全量上下文过慢
不需要全容器时用 @WebMvcTest 等切片,加快测试反馈。
面试高频问题
完整 30 道速查见 Spring Boot 面试题 30 道。
一句话总结
Web 层用 REST 映射 + @RestControllerAdvice;运维用 Actuator 并收紧暴露;测试按范围选 @SpringBootTest 或切片测试;数据访问先会 Starter + 数据源配置即可。