一、SpringBoot 请求与响应
1.1 环境与依赖
pom.xml 关键依赖
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency>
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> </dependencies>
|
版本注意:Spring Boot 3.x 校验注解包是 jakarta.validation.*,2.x 是 javax.validation.*,其余用法完全一致。
推荐项目结构
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| src/main/java/com/example/demo/ ├── DemoApplication.java # 启动类(必须在最外层包) ├── controller/ │ └── UserController.java # 接收请求、返回响应 ├── entity/ │ └── User.java # 数据库实体 ├── dto/ │ ├── UserQueryDTO.java # 接收请求参数的对象 │ └── UserCreateDTO.java ├── vo/ │ └── UserVO.java # 返回给前端的对象 └── common/ ├── R.java # 统一响应体 ├── GlobalExceptionHandler.java # 全局异常处理 └── LoginInterceptor.java # 拦截器
|
启动类
1 2 3 4 5 6
| @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
|
坑:启动类必须放在所有业务包的上层目录(如 com.example.demo),否则 controller、service 扫描不到,接口 404。
1.2 控制器基础
最小可用控制器
1 2 3 4 5 6 7 8 9 10
| @RestController @RequestMapping("/api/users") public class UserController {
@GetMapping("/{id}") public UserVO getById(@PathVariable Long id) { return new UserVO(id, "张三", 25); } }
|
请求映射注解对照表
| 注解 |
等价写法 |
用途 |
@GetMapping |
@RequestMapping(method = GET) |
查询 |
@PostMapping |
@RequestMapping(method = POST) |
新增 |
@PutMapping |
@RequestMapping(method = PUT) |
全量更新 |
@PatchMapping |
@RequestMapping(method = PATCH) |
局部更新 |
@DeleteMapping |
@RequestMapping(method = DELETE) |
删除 |
@RequestMapping |
可指定 path / method / params / headers |
需要精细化匹配时使用 |
精细化映射(限定参数/请求头)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| @RestController @RequestMapping("/api/orders") public class OrderController {
@GetMapping(value = "/search", params = "type=app") public List<OrderVO> searchFromApp(@RequestParam String keyword) { return orderService.search(keyword); }
@PostMapping(value = "/create", consumes = "application/json") public R<Long> create(@RequestBody OrderCreateDTO dto) { return R.ok(orderService.create(dto)); }
@GetMapping(value = "/export", produces = "application/json;charset=UTF-8") public R<List<OrderVO>> export() { return R.ok(orderService.listAll()); } }
|
1.3 HttpServletRequest / HttpServletResponse(前置了解)
一句话:SpringMVC 里所有参数注解(@PathVariable、@RequestParam、@RequestBody…)都是 Tomcat 把 HTTP 报文解析成 HttpServletRequest 之后,从里面取值再填到你的方法参数上。看懂原生对象,后面 9 种参数接收方式就不用死记硬背。
1.3.1 一次 HTTP 请求的完整链路
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| 浏览器发起 HTTP 请求 ↓ Tomcat 解析报文 → 封装成 HttpServletRequest + HttpServletResponse ↓ Filter 过滤器链(编码 / 跨域 / 全局日志) ↓ DispatcherServlet(前端控制器,统一入口) ↓ HandlerMapping → 根据 URL 找到对应的 Controller 方法 ↓ HandlerAdapter → 参数解析器把 Request 里的数据绑定到方法参数上 ↓ Controller 方法执行(业务处理) ↓ 返回值 → HttpMessageConverter(Jackson)转成 JSON ↓ 写回 HttpServletResponse → Tomcat 组装 HTTP 响应 → 浏览器
|
核心结论:Controller 方法的每个参数,都是由 HandlerMethodArgumentResolver(参数解析器)从 HttpServletRequest 里解析出来并做类型转换的。注解的作用只是告诉它——去哪儿取、怎么转、要不要必填。
1.3.2 HttpServletRequest 常用 API
| 方法 |
作用 |
示例返回值 |
getMethod() |
请求方式 |
GET / POST |
getRequestURI() |
请求路径(不含域名) |
/api/users/1 |
getRequestURL() |
完整 URL |
http://localhost:8080/api/users/1 |
getQueryString() |
URL 上的查询串 |
page=1&size=10 |
getParameter(name) |
取请求参数(URL 或表单) |
1 |
getParameterValues(name) |
取同名多值参数 |
["1","2","3"] |
getParameterMap() |
所有参数 |
{page=["1"], size=["10"]} |
getHeader(name) |
取请求头 |
Bearer xxx |
getHeaderNames() |
所有请求头名 |
枚举 |
getCookies() |
取所有 Cookie |
Cookie[] |
getInputStream() / getReader() |
读请求体(JSON 原始报文) |
只能读一次 |
getContentType() |
请求体类型 |
application/json |
getRemoteAddr() |
客户端 IP |
127.0.0.1 |
getSession() |
获取 Session |
HttpSession |
getAttribute(name) |
取请求域属性(配合拦截器传值) |
setAttribute 存进去的东西 |
getServletContext() |
应用上下文 |
ServletContext |
1.3.3 HttpServletResponse 常用 API
| 方法 |
作用 |
setStatus(int) |
设置状态码(如 401/404) |
setContentType(String) |
设置响应类型 |
setCharacterEncoding(String) |
设置编码 |
setHeader(name, value) |
设置响应头 |
addHeader(name, value) |
追加响应头(可重复) |
getWriter() |
字符输出流(写文本/JSON) |
getOutputStream() |
字节输出流(写文件/图片) |
sendRedirect(url) |
重定向 |
addCookie(Cookie) |
写 Cookie 给浏览器 |
sendError(404) |
直接返回错误页 |
1.3.4 不用任何注解,手写接口
理解了原生对象,下面这段代码就是 SpringMVC 帮你做的事的”展开版”:
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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| @RestController @RequestMapping("/api/raw") public class RawController {
@GetMapping("/user") public void getUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
String idStr = request.getParameter("id");
Long id = Long.valueOf(idStr);
UserVO user = userService.getById(id);
response.setStatus(HttpServletResponse.SC_OK); response.setContentType("application/json;charset=UTF-8"); response.getWriter().write(JSON.toJSONString(R.ok(user))); }
@PostMapping("/create") public void createUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
String body = request.getReader().lines() .collect(Collectors.joining(System.lineSeparator()));
UserCreateDTO dto = JSON.parseObject(body, UserCreateDTO.class); Long id = userService.create(dto);
response.setStatus(HttpServletResponse.SC_CREATED); response.setContentType("application/json;charset=UTF-8"); response.getWriter().write(JSON.toJSONString(R.ok(id))); } }
|
1.3.5 注解 ↔ 原生 API 对照表
| Spring 注解 |
等价于原生写法 |
@RequestParam("id") Long id |
request.getParameter("id") + 类型转换 |
@PathVariable("id") Long id |
从 request.getRequestURI() 里截取路径段 |
@RequestBody UserDTO dto |
request.getReader() 读流 + Jackson 反序列化 |
@RequestHeader("Authorization") |
request.getHeader("Authorization") |
@CookieValue("JSESSIONID") |
遍历 request.getCookies() 找同名 Cookie |
UserQueryDTO query(无注解) |
遍历 request.getParameterMap() 按属性名反射赋值 |
@RequestParam List<Long> ids |
request.getParameterValues("ids") + 逐个转换 |
@RequestParam MultipartFile file |
request.getParts() 取上传的二进制部分 |
@ResponseBody |
response.getWriter().write(JSON.toJSONString(obj)) |
@Valid |
手动 if (dto.getUsername() == null) { ... } |
1.3.6 什么时候必须用原生对象
日常 CRUD 优先用注解,原生对象只在以下场景兜底:
- 文件下载 / 验证码 / 图片:需要直接操作
response.getOutputStream()
- 写 Cookie:
response.addCookie(new Cookie("token", token))
- 拦截器与 Controller 传值:
request.setAttribute("userId", 1L) → Controller 里 request.getAttribute("userId")
- 获取真实 IP:经过 Nginx 代理时要读
X-Forwarded-For 头
- 接口验签:需要读取原始请求体做签名比对(此时不能用
@RequestBody,否则流已被消费)
- 导出 Excel / CSV:直接写输出流,避免大文件撑爆内存
1.3.7 两个必知的坑
1 2 3 4 5 6 7 8
|
response.getWriter().write("xxx");
|
1.4 接收请求参数(9 种常见场景)
建议先看 1.3 HttpServletRequest(前置了解)。下面这些注解本质上都是从原生 Request 里取值,理解底层后下面的写法就不需要死记。
1.4.1 @PathVariable 路径参数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| @GetMapping("/{id}") public R<UserVO> getById(@PathVariable("id") Long id) { return R.ok(userService.getById(id)); }
@GetMapping("/{id}") public R<UserVO> getById(@PathVariable Long id) { ... }
@GetMapping("/{userId}/orders/{year}") public R<List<OrderVO>> userOrders(@PathVariable Long userId, @PathVariable Integer year) { return R.ok(orderService.listByUserAndYear(userId, year)); }
@GetMapping("/dept/{deptId}/user/{userId}") public R<Map<String, String>> test(@PathVariable Map<String, String> pathVars) { return R.ok(pathVars); }
|
1.4.2 @RequestParam 查询参数
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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| @GetMapping("url") public R<List<UserVO>> list(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer size) { return R.ok(userService.page(page, size)); }
@GetMapping("url") public void list(User user) {
}
@GetMapping("url") public void list(@RequestParam List<String> list) { }
@GetMapping("url") public void list(@RequestParam(name="name") String userName) { }
@GetMapping("/search") public R<List<UserVO>> search(@RequestParam(required = false) String keyword) { return R.ok(userService.search(keyword)); }
@GetMapping("url") public void list(@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") LocalDataTime ldt) { ldt->就是LocalDataTime的日期类型 }
@GetMapping("url") public void list(@RequestBody User user) { }
@GetMapping("/set/{id}/{name}") public void list(@PathVarivable Integer id, @PathVariable ) { }
|
@RequestParam 三个属性:
| 属性 |
说明 |
value/name |
绑定的请求参数名(与变量名一致时可省略) |
required |
是否必传,默认 true,不传抛 400 |
defaultValue |
默认值,设置后 required 自动失效为 false |
1.4.3 @RequestBody JSON 请求体
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| @Data public class UserCreateDTO { @NotBlank(message = "用户名不能为空") private String username;
@NotBlank(message = "密码不能为空") @Size(min = 6, max = 20, message = "密码长度 6-20 位") private String password;
@Email(message = "邮箱格式不正确") private String email;
private Integer age; }
@PostMapping public R<Long> create(@RequestBody UserCreateDTO dto) { return R.ok(userService.create(dto)); }
|
规则:
- 一个方法只能有一个
@RequestBody
- 前端必须带
Content-Type: application/json,否则报 415
- 接收数组:
@RequestBody List<Long> ids
1 2 3 4 5 6
| @PostMapping("/batch-delete") public R<Void> batchDelete(@RequestBody List<Long> ids) { userService.removeByIds(ids); return R.ok(); }
|
1.4.4 无注解:表单 / 对象自动绑定
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| @Data public class UserQueryDTO { private String keyword; private Integer status; private Integer page = 1; private Integer size = 10; }
@GetMapping("/list") public R<List<UserVO>> list(UserQueryDTO query) { return R.ok(userService.list(query)); }
|
Spring 会把请求参数按属性名自动塞进对象。这是最省事的写法,查询类接口优先用它。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| @GetMapping("/header") public R<String> header(@RequestHeader("Authorization") String token) { return R.ok(token); }
@GetMapping("/ua") public R<String> ua(@RequestHeader(value = "User-Agent", defaultValue = "unknown") String ua) { return R.ok(ua); }
@GetMapping("/all-headers") public R<Map<String, String>> allHeaders(@RequestHeader Map<String, String> headers) { return R.ok(headers); }
@GetMapping("/cookie") public R<String> cookie(@CookieValue(value = "JSESSIONID", required = false) String jsessionId) { return R.ok(jsessionId); }
|
1.4.6 数组 / 集合参数
1 2 3 4 5 6 7 8 9 10 11
| @GetMapping("/ids") public R<List<UserVO>> byIds(@RequestParam List<Long> ids) { return R.ok(userService.listByIds(ids)); }
@GetMapping("/ids2") public R<List<UserVO>> byIds2(@RequestParam Long[] ids) { return R.ok(userService.listByIds(Arrays.asList(ids))); }
|
1.4.7 日期时间参数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| @Data public class ReportQueryDTO { @DateTimeFormat(pattern = "yyyy-MM-dd") private LocalDate startDate;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") private LocalDateTime endDate; }
@GetMapping("/report") public R<List<ReportVO>> report(ReportQueryDTO query) { return R.ok(reportService.list(query)); }
|
全局配置(免得每个字段都写注解):
1 2 3 4 5
| spring: mvc: format: date: yyyy-MM-dd date-time: yyyy-MM-dd HH:mm:ss
|
1.4.8 文件上传 MultipartFile
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 33 34 35
| @RestController @RequestMapping("/api/files") public class FileController {
@PostMapping("/upload") public R<String> upload(@RequestParam("file") MultipartFile file) throws IOException { if (file.isEmpty()) { return R.fail("文件为空"); }
String originalName = file.getOriginalFilename(); long size = file.getSize(); String ext = originalName.substring(originalName.lastIndexOf(".")); String newName = UUID.randomUUID() + ext;
Path target = Paths.get("D:/uploads/" + newName); Files.createDirectories(target.getParent()); file.transferTo(target);
return R.ok("/files/" + newName); }
@PostMapping("/upload-batch") public R<List<String>> uploadBatch(@RequestParam("files") List<MultipartFile> files, @RequestParam String bizType) throws IOException { List<String> urls = new ArrayList<>(); for (MultipartFile f : files) { String url = storageService.save(f, bizType); urls.add(url); } return R.ok(urls); } }
|
上传大小限制:
1 2 3 4 5
| spring: servlet: multipart: max-file-size: 10MB max-request-size: 100MB
|
1.4.9 原生 HttpServletRequest / HttpServletResponse
完整 API 说明见 1.3,这里只列最常用的取法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| @GetMapping("/raw") public void raw(HttpServletRequest request, HttpServletResponse response) throws IOException { String method = request.getMethod(); String uri = request.getRequestURI(); String ip = request.getRemoteAddr(); String ua = request.getHeader("User-Agent"); String token = request.getParameter("token");
response.setContentType("application/json;charset=UTF-8"); response.getWriter().write("{\"code\":0,\"msg\":\"ok\"}"); }
public static String getIpAddr(HttpServletRequest request) { String ip = request.getHeader("X-Forwarded-For"); if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("X-Real-IP"); } if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } return ip != null && ip.contains(",") ? ip.split(",")[0].trim() : ip; }
|
参数接收方式速查表
| 场景 |
写法 |
前端传参方式 |
/users/1 |
@PathVariable Long id |
URL 路径 |
?page=1 |
@RequestParam Integer page |
URL 查询串 / 表单 |
{"name":"x"} |
@RequestBody XxxDTO dto |
JSON 请求体 |
?a=1&b=2 多参数 |
XxxDTO dto(无注解) |
查询串 / 表单自动绑定 |
| 请求头 |
@RequestHeader("Authorization") |
Header |
| Cookie |
@CookieValue("JSESSIONID") |
Cookie |
| 逗号分隔 / 重复 key |
@RequestParam List<Long> ids |
ids=1,2,3 |
| 日期 |
@DateTimeFormat(pattern=...) |
2026-10-15 |
| 文件 |
@RequestParam MultipartFile file |
multipart/form-data |
| 拿原生对象 |
HttpServletRequest request |
— |
1.5 参数校验 @Valid
常用校验注解
| 注解 |
作用 |
适用类型 |
@NotNull |
不能为 null |
任意 |
@NotEmpty |
不能为 null 且长度 > 0 |
字符串/集合 |
@NotBlank |
不能为 null 且去空格后长度 > 0 |
字符串 |
@Size |
长度范围 |
字符串/集合 |
@Min / @Max |
数值范围 |
数字 |
@Pattern |
正则 |
字符串 |
@Email |
邮箱格式 |
字符串 |
@Past / @Future |
时间必须过去 / 将来 |
日期 |
@Valid |
嵌套对象级联校验 |
对象 |
使用
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 33 34 35 36 37 38 39 40 41
| @Data public class UserCreateDTO {
@NotBlank(message = "用户名不能为空") @Size(min = 2, max = 20, message = "用户名长度 2-20") private String username;
@NotBlank(message = "密码不能为空") @Pattern(regexp = "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{6,20}$", message = "密码需 6-20 位且包含字母和数字") private String password;
@NotNull(message = "年龄不能为空") @Min(value = 1, message = "年龄最小 1 岁") @Max(value = 150, message = "年龄最大 150 岁") private Integer age;
@NotEmpty(message = "角色不能为空") private List<Long> roleIds;
@Valid @NotNull(message = "地址不能为空") private AddressDTO address; }
@Data public class AddressDTO { @NotBlank(message = "城市不能为空") private String city; }
@PostMapping public R<Long> create(@Valid @RequestBody UserCreateDTO dto) { return R.ok(userService.create(dto)); }
@GetMapping("/list") public R<List<UserVO>> list(@Validated UserQueryDTO query) { ... }
|
分组校验(新增/编辑用同一 DTO)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| public class ValidationGroups { public interface Create {} public interface Update {} }
@Data public class UserDTO { @Null(groups = Create.class, message = "新增时 id 必须为空") @NotNull(groups = Update.class, message = "编辑时 id 不能为空") private Long id;
@NotBlank(groups = {Create.class, Update.class}, message = "用户名不能为空") private String username; }
@PostMapping public R<Long> create(@Validated(ValidationGroups.Create.class) @RequestBody UserDTO dto) { ... }
@PutMapping public R<Void> update(@Validated(ValidationGroups.Update.class) @RequestBody UserDTO dto) { ... }
|
1.6 响应数据
1.6.1 直接返回对象(自动转 JSON)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| @Data @AllArgsConstructor public class UserVO { private Long id; private String name; private Integer age;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private LocalDateTime createTime; }
@GetMapping("/{id}") public UserVO getById(@PathVariable Long id) { return userService.getById(id); }
|
1.6.2 ResponseEntity(控制状态码和响应头)
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
| @PostMapping public ResponseEntity<UserVO> create(@RequestBody UserCreateDTO dto) { UserVO vo = userService.create(dto); return ResponseEntity.status(HttpStatus.CREATED).body(vo); }
@GetMapping("/download/{fileName}") public ResponseEntity<byte[]> download(@PathVariable String fileName) throws IOException { Path path = Paths.get("D:/uploads/" + fileName); byte[] data = Files.readAllBytes(path);
HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); headers.setContentDispositionFormData("attachment", URLEncoder.encode(fileName, StandardCharsets.UTF_8.name()));
return new ResponseEntity<>(data, headers, HttpStatus.OK); }
@DeleteMapping("/{id}") public ResponseEntity<Void> delete(@PathVariable Long id) { userService.removeById(id); return ResponseEntity.noContent().build(); }
|
1.6.3 统一响应体(项目必配)
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
| @Data @NoArgsConstructor @AllArgsConstructor public class R<T> implements Serializable { private Integer code; private String message; private T data; private Long timestamp = System.currentTimeMillis();
public static <T> R<T> ok() { return new R<>(0, "success", null, System.currentTimeMillis()); }
public static <T> R<T> ok(T data) { return new R<>(0, "success", data, System.currentTimeMillis()); }
public static <T> R<T> fail(String message) { return new R<>(500, message, null, System.currentTimeMillis()); }
public static <T> R<T> fail(Integer code, String message) { return new R<>(code, message, null, System.currentTimeMillis()); } }
|
使用:
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
| @RestController @RequestMapping("/api/users") public class UserController {
@GetMapping("/{id}") public R<UserVO> getById(@PathVariable Long id) { return R.ok(userService.getById(id)); }
@GetMapping("/page") public R<PageResult<UserVO>> page(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer size) { return R.ok(userService.page(page, size)); }
@PostMapping public R<Long> create(@Valid @RequestBody UserCreateDTO dto) { return R.ok(userService.create(dto)); }
@DeleteMapping("/{id}") public R<Void> delete(@PathVariable Long id) { userService.removeById(id); return R.ok(); } }
|
前端拿到的统一结构:
1 2 3 4 5 6
| { "code": 0, "message": "success", "data": { "id": 1, "name": "张三", "age": 25 }, "timestamp": 1760600000000 }
|
1.6.4 响应包装的偷懒方案:ResponseBodyAdvice
不想每个方法都手写 R.ok(...),用这个自动包装:
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
| @RestControllerAdvice(basePackages = "com.example.demo.controller") public class GlobalResponseAdvice implements ResponseBodyAdvice<Object> {
@Override public boolean supports(MethodParameter returnType, Class<?> converterType) { return !returnType.getParameterType().isAssignableFrom(R.class) && !returnType.getParameterType().isAssignableFrom(ResponseEntity.class); }
@Override public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<?> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) { if (body instanceof String) { try { response.getHeaders().setContentType(MediaType.APPLICATION_JSON); return new ObjectMapper().writeValueAsString(R.ok(body)); } catch (JsonProcessingException e) { return R.fail(e.getMessage()); } } return R.ok(body); } }
|
这样 Controller 可以直接返回业务对象:
1 2 3 4
| @GetMapping("/{id}") public UserVO getById(@PathVariable Long id) { return userService.getById(id); }
|
1.7 全局异常处理
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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| @RestControllerAdvice @Slf4j public class GlobalExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class) public R<Void> handleValidException(MethodArgumentNotValidException e) { String msg = e.getBindingResult().getFieldErrors().stream() .map(f -> f.getField() + ": " + f.getDefaultMessage()) .collect(Collectors.joining(", ")); log.warn("参数校验失败: {}", msg); return R.fail(400, msg); }
@ExceptionHandler(ConstraintViolationException.class) public R<Void> handleConstraintViolation(ConstraintViolationException e) { String msg = e.getConstraintViolations().stream() .map(ConstraintViolation::getMessage) .collect(Collectors.joining(", ")); return R.fail(400, msg); }
@ExceptionHandler(MethodArgumentTypeMismatchException.class) public R<Void> handleTypeMismatch(MethodArgumentTypeMismatchException e) { return R.fail(400, "参数 " + e.getName() + " 类型错误"); }
@ExceptionHandler(HttpRequestMethodNotSupportedException.class) public R<Void> handleMethodNotSupported(HttpRequestMethodNotSupportedException e) { return R.fail(405, "不支持的请求方法: " + e.getMethod()); }
@ExceptionHandler(HttpMessageNotReadableException.class) public R<Void> handleNotReadable(HttpMessageNotReadableException e) { return R.fail(400, "请求体 JSON 格式错误"); }
@ExceptionHandler(MissingServletRequestParameterException.class) public R<Void> handleMissingParam(MissingServletRequestParameterException e) { return R.fail(400, "缺少必填参数: " + e.getParameterName()); }
@ExceptionHandler(MaxUploadSizeExceededException.class) public R<Void> handleMaxUpload(MaxUploadSizeExceededException e) { return R.fail(400, "文件大小超出限制"); }
@ExceptionHandler(BizException.class) public R<Void> handleBizException(BizException e) { log.error("业务异常: ", e); return R.fail(e.getCode(), e.getMessage()); }
@ExceptionHandler(Exception.class) public R<Void> handleException(Exception e) { log.error("系统异常: ", e); return R.fail(500, "服务器开小差了,请稍后重试"); } }
|
自定义业务异常:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| @Data @EqualsAndHashCode(callSuper = true) public class BizException extends RuntimeException { private Integer code;
public BizException(String message) { super(message); this.code = 500; }
public BizException(Integer code, String message) { super(message); this.code = code; } }
if (user == null) { throw new BizException(404, "用户不存在"); }
|
1.8 拦截器与过滤器
拦截器 HandlerInterceptor(最常用:登录校验)
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
| @Component public class LoginInterceptor implements HandlerInterceptor {
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String token = request.getHeader("Authorization"); if (token == null || !TokenUtil.verify(token)) { response.setContentType("application/json;charset=UTF-8"); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.getWriter().write("{\"code\":401,\"message\":\"未登录\"}"); return false; } request.setAttribute("userId", TokenUtil.getUserId(token)); return true; }
@Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) { }
@Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { } }
|
注册拦截器:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| @Configuration public class WebConfig implements WebMvcConfigurer {
@Autowired private LoginInterceptor loginInterceptor;
@Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(loginInterceptor) .addPathPatterns("/api/**") .excludePathPatterns( "/api/auth/login", "/api/auth/register", "/api/files/**", "/error" ); } }
|
过滤器 Filter(更底层,处理编码、跨域日志)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| @Component @Order(1) public class LogFilter implements Filter {
@Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; long start = System.currentTimeMillis(); try { chain.doFilter(req, res); } finally { long cost = System.currentTimeMillis() - start; System.out.printf("%s %s 耗时 %dms%n", request.getMethod(), request.getRequestURI(), cost); } } }
|
拦截器 vs 过滤器
| 对比项 |
Filter |
Interceptor |
| 归属 |
Servlet 规范 |
SpringMVC |
| 生效范围 |
所有请求(含静态资源) |
只拦截 Controller |
| 拿到的对象 |
原生 Request/Response |
还能拿到 Handler 方法信息 |
| 依赖注入 |
支持(注册为 Bean) |
支持 |
| 典型用途 |
编码、跨域、全局日志、XSS 过滤 |
登录鉴权、权限、接口耗时统计 |
1.9 跨域 CORS
方案一:配置类(推荐)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| @Configuration public class CorsConfig implements WebMvcConfigurer {
@Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOriginPatterns("*") .allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS") .allowedHeaders("*") .exposedHeaders("Authorization", "Content-Disposition") .allowCredentials(true) .maxAge(3600); } }
|
方案二:单接口注解
1 2 3
| @CrossOrigin(origins = "http://localhost:5173", allowCredentials = "true") @GetMapping("/{id}") public R<UserVO> getById(@PathVariable Long id) { ... }
|
坑:allowCredentials(true) 时 allowedOrigins **不能写 "*"**,要用 allowedOriginPatterns("*")。
1.10 Jackson 常用注解(控制 JSON 字段)
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
| @Data public class UserVO {
@JsonProperty("user_name") private String userName;
@JsonIgnore private String password;
@JsonInclude(JsonInclude.Include.NON_NULL) private String remark;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private LocalDateTime createTime;
@JsonSerialize(using = BigDecimalSerializer.class) private BigDecimal amount;
@JsonFormat(shape = JsonFormat.Shape.OBJECT) private StatusEnum status; }
|
全局配置:
1 2 3 4 5 6 7
| spring: jackson: date-format: yyyy-MM-dd HH:mm:ss time-zone: GMT+8 default-property-inclusion: non_null deserialization: fail-on-unknown-properties: false
|
1.11 常见坑与排查
| 现象 |
原因 |
解决 |
| 接口 404 |
① 启动类包路径太深 ② 路径拼写错 ③ 没加 @RestController |
启动类放最外层包;检查 @RequestMapping 拼接结果 |
@RequestBody 报 415 |
前端没带 Content-Type: application/json |
axios 设置 headers: {'Content-Type':'application/json'} |
| 日期参数 400 |
字符串无法转 LocalDate |
加 @DateTimeFormat 或全局 spring.mvc.format |
| Long 传到前端精度丢失 |
JS 数字最大安全值 2^53-1,id 太长 |
全局把 Long 序列化为 String,或字段改 String |
| 中文乱码 |
响应未指定 UTF-8 |
produces = "application/json;charset=UTF-8" |
| 参数接收到 null |
① 名字不一致 ② 用了 @RequestBody 但传的是表单 |
核对参数名;表单提交去掉 @RequestBody |
| OPTIONS 预检失败 |
跨域未放行 OPTIONS |
CORS 配置里加上 OPTIONS 方法 |
@Valid 不生效 |
忘了加 @Valid / 嵌套对象没加 |
@Valid @RequestBody;嵌套字段加 @Valid |
| 拦截器不生效 |
没注册到 WebMvcConfigurer,或被 excludePathPatterns 排除了 |
检查注册代码和路径匹配规则 |
Long 精度丢失全局处理
1 2 3 4 5 6 7 8 9 10 11 12 13
| @Configuration public class JacksonConfig {
@Bean public Jackson2ObjectMapperBuilderCustomizer jacksonCustomizer() { return builder -> { builder.serializerByType(Long.class, ToStringSerializer.instance); builder.serializerByType(Long.TYPE, ToStringSerializer.instance); builder.serializerByType(BigInteger.class, ToStringSerializer.instance); }; } }
|
1.12 完整示例:用户模块接口
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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| @RestController @RequestMapping("/api/users") @Validated public class UserController {
@Autowired private UserService userService;
@GetMapping public R<PageResult<UserVO>> page(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer size, @RequestParam(required = false) String keyword) { return R.ok(userService.page(page, size, keyword)); }
@GetMapping("/{id}") public R<UserVO> getById(@PathVariable Long id) { UserVO vo = userService.getById(id); if (vo == null) { throw new BizException(404, "用户不存在"); } return R.ok(vo); }
@PostMapping public R<Long> create(@Valid @RequestBody UserCreateDTO dto) { return R.ok(userService.create(dto)); }
@PutMapping("/{id}") public R<Void> update(@PathVariable Long id, @Valid @RequestBody UserUpdateDTO dto) { userService.update(id, dto); return R.ok(); }
@PatchMapping("/{id}/status") public R<Void> updateStatus(@PathVariable Long id, @RequestParam Integer status) { userService.updateStatus(id, status); return R.ok(); }
@DeleteMapping("/{id}") public R<Void> delete(@PathVariable Long id) { userService.removeById(id); return R.ok(); }
@PostMapping("/batch-delete") public R<Void> batchDelete(@RequestBody List<Long> ids) { userService.removeByIds(ids); return R.ok(); }
@GetMapping("/export") public void export(HttpServletResponse response) throws IOException { List<UserVO> list = userService.listAll(); response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("用户列表.xlsx", "UTF-8")); userService.exportExcel(list, response.getOutputStream()); } }
|
配套 DTO / VO:
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 33 34 35 36 37 38 39 40 41 42 43 44
| @Data public class UserCreateDTO { @NotBlank(message = "用户名不能为空") private String username;
@NotBlank(message = "密码不能为空") @Size(min = 6, max = 20, message = "密码 6-20 位") private String password;
@Email(message = "邮箱格式不正确") private String email;
@NotNull(message = "年龄不能为空") @Min(1) @Max(150) private Integer age; }
@Data public class UserVO { private String id; private String username; private String email; private Integer age; private String statusDesc;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private LocalDateTime createTime; }
@Data @AllArgsConstructor public class PageResult<T> { private List<T> records; private Long total; private Integer page; private Integer size;
public static <T> PageResult<T> of(List<T> records, Long total, Integer page, Integer size) { return new PageResult<>(records, total, page, size); } }
|
二、Spring 常用注解
注解本身只是”标记”,真正干活的是 Spring 容器在启动时扫描这些标记,然后注册 Bean、注入依赖、织入代理。理解”谁在什么时候读这个注解”,比死记注解名字更重要。
2.1 组件注册注解(把类交给容器管理)
2.1.1 四大组件注解
| 注解 |
用在哪一层 |
额外能力 |
@Component |
通用组件(工具类、处理器等) |
无,最基础 |
@Service |
业务层 |
无(语义标记),本质就是 @Component |
@Repository |
数据访问层 |
会把数据库原生异常转换成 Spring 的 DataAccessException |
@Controller |
控制层 |
配合视图解析器返回页面 |
@RestController |
控制层(接口) |
=@Controller + @ResponseBody,返回值直接写成 JSON |
1 2 3 4 5 6 7 8 9 10 11 12
| @Component public class SmsSender { }
@Service("userService") public class UserServiceImpl implements UserService { }
@Repository public class UserDao { }
@RestController @RequestMapping("/api/user") public class UserController { }
|
坑:类名前两个字母都是大写时(如 URLParser),默认 Bean 名不转小写,仍是 URLParser。
2.1.2 @Configuration + @Bean(注册第三方类)
第三方 jar 里的类没法加 @Component,就用配置类 + @Bean 方法手动 new 出来交给容器。
或者使用 @import
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
| @import(FastException.class)
@Configuration public class AppConfig {
@Scope("protoType") @Bean public RestTemplate restTemplate() { return new RestTemplate(); }
@Bean(name = "bizPool", initMethod = "init", destroyMethod = "shutdown") public MyThreadPool bizPool() { return new MyThreadPool(10); }
@Bean public UserClient userClient(RestTemplate restTemplate) { return new UserClient(restTemplate); } }
|
@Configuration 与 @Component 里写 @Bean 的区别:
| 写法 |
内部调用另一个 @Bean 方法 |
原因 |
@Configuration(默认 proxyBeanMethods = true) |
返回容器里的同一个单例 |
配置类被 CGLIB 代理,方法调用被拦截 |
@Component 或 @Configuration(proxyBeanMethods = false) |
每次调用都new 一个新对象 |
没有代理,就是普通 Java 方法调用 |
1 2 3 4 5 6 7 8 9 10
| @Configuration public class DemoConfig { @Bean public A a() { return new A(); }
@Bean public B b() { return new B(a()); } }
|
2.1.3 扫描与导入
| 注解 |
作用 |
@ComponentScan |
指定扫描哪些包下的 @Component 类,默认扫描启动类所在包及子包 |
@Import |
直接导入配置类 / 普通类 /ImportSelector / ImportBeanDefinitionRegistrar |
@ImportResource |
导入老式 XML 配置 |
1 2 3 4
| @SpringBootApplication @ComponentScan(basePackages = {"com.demo", "com.common.util"}) @Import({RedisConfig.class, SmsSender.class}) public class DemoApplication { }
|
坑:启动类放在 com.demo.app 下,而 Service 在 com.demo.service,默认扫描不到,报 No qualifying bean。启动类应放在最顶层包。
2.1.4 作用域、懒加载、优先级
| 注解 |
作用 |
@Scope("singleton") |
单例(默认),容器里只有一个 |
@Scope("prototype") |
多例,每次获取都 new |
@Scope("request") / @Scope("session") |
Web 环境下每个请求 / 会话一个 |
@Lazy |
第一次被使用时才创建(默认启动时就创建) |
@Primary |
同类型多个 Bean 时,默认注入这个 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| @Component @Scope("prototype") public class ExportTask { }
@Component @Lazy public class HeavyClient { }
@Configuration public class DsConfig { @Bean @Primary public DataSource master() { ... }
@Bean public DataSource slave() { ... } }
|
坑:单例 Bean 里注入 prototype Bean,只会在单例创建时注入一次,之后一直是同一个对象。需要每次新对象应注入 ObjectProvider<ExportTask> 并调用 getObject()。
2.2 依赖注入注解
2.2.1 @Autowired / @Qualifier / @Resource
| 注解 |
来源 |
匹配方式 |
能否 required=false |
@Autowired |
Spring |
先按类型,多个时再按变量名 |
能 |
@Qualifier("名字") |
Spring |
配合 @Autowired 指定 Bean 名 |
— |
@Resource(name = "x") |
JDK(jakarta.annotation) |
先按名字,找不到再按类型 |
不能 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| public interface PayService { void pay(); }
@Service("aliPay") public class AliPayService implements PayService { ... } @Service("wxPay") public class WxPayService implements PayService { ... }
@RestController public class PayController {
@Autowired @Qualifier("wxPay") private PayService payService;
@Resource(name = "aliPay") private PayService aliPay;
@Autowired private Map<String, PayService> payMap;
@Autowired private List<PayService> payList;
@Autowired(required = false) private SmsSender smsSender; }
|
2.2.2 三种注入方式对比
| 方式 |
写法 |
推荐度 |
说明 |
| 字段注入 |
@Autowired private A a; |
不推荐 |
写起来简单,但无法 final、不方便单测、IDEA 有警告 |
| Setter 注入 |
@Autowired public void setA(A a) |
可选依赖时用 |
— |
| 构造器注入 |
构造方法参数 |
推荐 |
可以 final,依赖一目了然;只有一个构造器时可以省略 @Autowired |
1 2 3 4 5 6
| @Service @RequiredArgsConstructor public class OrderService { private final UserService userService; private final OrderMapper orderMapper; }
|
坑:构造器注入遇到循环依赖(A 依赖 B,B 依赖 A)会直接启动失败。Spring Boot 2.6+ 默认禁止循环依赖,正确做法是拆分逻辑;临时方案是在一侧参数上加 @Lazy。
2.2.3 @Value(注入单个配置值)
1 2 3 4
| app: name: demo timeout: 3000 white-list: a,b,c
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| @Component public class AppProps {
@Value("${app.name}") private String name;
@Value("${app.timeout:5000}") private Integer timeout;
@Value("${app.white-list}") private List<String> whiteList;
@Value("#{${app.timeout} * 2}") private Integer doubleTimeout;
@Value("#{T(java.lang.Math).random()}") private Double random; }
|
坑:@Value 不能注入 static 字段(静态字段会是 null);在 new 出来的对象里也不生效,必须是容器管理的 Bean。
2.3 配置属性注解
2.3.1 @ConfigurationProperties(批量绑定,推荐)
1 2 3 4 5 6 7 8 9 10
| sms: enabled: true access-key: AK123 secret-key: SK456 templates: login: T001 register: T002 retry: times: 3 interval: 1000
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| @Data @Component @ConfigurationProperties(prefix = "sms") public class SmsProperties { private Boolean enabled; private String accessKey; private String secretKey; private Map<String, String> templates; private Retry retry = new Retry();
@Data public static class Retry { private Integer times; private Long interval; } }
|
1 2 3 4
| @Configuration @EnableConfigurationProperties(SmsProperties.class) public class SmsAutoConfig { }
|
@Value 与 @ConfigurationProperties 对比:
| 对比项 |
@Value |
@ConfigurationProperties |
| 绑定方式 |
一个一个注入 |
按前缀批量绑定 |
宽松绑定(access-key → accessKey) |
不支持 |
支持 |
| SpEL 表达式 |
支持 |
不支持 |
| 复杂类型(Map、嵌套对象) |
麻烦 |
天然支持 |
配合 @Validated 做校验 |
不支持 |
支持 |
1 2 3 4 5 6 7
| @Data @Validated @ConfigurationProperties(prefix = "sms") public class SmsProperties { @NotBlank private String accessKey; }
|
小技巧:引入 spring-boot-configuration-processor 依赖后,在 yml 里写配置会有自动提示。
2.3.2 @PropertySource(加载额外的 properties 文件)
1 2 3
| @Configuration @PropertySource(value = "classpath:custom.properties", encoding = "UTF-8") public class CustomConfig { }
|
坑:@PropertySource 默认不支持 yml,只能加载 .properties;需要 yml 的话要自定义 PropertySourceFactory。
2.4 条件注解(满足条件才注册 Bean)
条件注解是 Spring Boot 自动配置的核心:引入了某个 jar、配置了某个开关、容器里还没有某个 Bean,满足这些条件才去创建默认的 Bean。
2.4.1 常用条件注解一览
| 注解 |
条件成立的情况 |
典型用途 |
@ConditionalOnProperty |
配置项存在且等于指定值 |
功能开关 |
@ConditionalOnClass |
classpath 中有某个类 |
引入了某个 jar 才生效 |
@ConditionalOnMissingClass |
classpath 中没有某个类 |
— |
@ConditionalOnBean |
容器中已有某个 Bean |
依赖其他组件 |
@ConditionalOnMissingBean |
容器中没有某个 Bean |
提供默认实现,用户可自定义覆盖 |
@ConditionalOnWebApplication |
当前是 Web 应用 |
只在 Web 环境注册拦截器等 |
@ConditionalOnNotWebApplication |
不是 Web 应用 |
— |
@ConditionalOnExpression |
SpEL 表达式结果为 true |
组合条件 |
@ConditionalOnResource |
classpath 中有某个资源文件 |
— |
@ConditionalOnJava |
Java 版本符合要求 |
— |
@ConditionalOnSingleCandidate |
某类型只有一个 Bean,或有一个 @Primary |
— |
@Profile |
当前激活的环境匹配 |
区分 dev / test / prod |
@Conditional(XxxCondition.class) |
自定义 Condition 返回 true |
上面这些都不够用时 |
2.4.2 @ConditionalOnProperty(功能开关,最常用)
1 2 3
| feature: sms: enabled: true
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| @Configuration public class SmsConfig {
@Bean @ConditionalOnProperty(prefix = "feature.sms", name = "enabled", havingValue = "true") public SmsSender smsSender() { return new AliyunSmsSender(); }
@Bean @ConditionalOnProperty(name = "feature.cache.enabled", havingValue = "true", matchIfMissing = true) public CacheManager cacheManager() { return new ConcurrentMapCacheManager(); } }
|
| 配置情况 |
havingValue="true" |
havingValue="true", matchIfMissing=true |
配了 true |
成立 |
成立 |
配了 false |
不成立 |
不成立 |
| 没配 |
不成立 |
成立 |
坑:不写 havingValue 时,只要配置值不是 false 就成立(包括配了任意字符串)。
2.4.3 @ConditionalOnClass / @ConditionalOnMissingBean(写 starter 的标准套路)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| @Configuration @ConditionalOnClass(RedisTemplate.class) @EnableConfigurationProperties(LockProperties.class) public class DistributedLockAutoConfig {
@Bean @ConditionalOnMissingBean public LockService lockService(RedisTemplate<String, Object> redisTemplate) { return new RedisLockService(redisTemplate); }
@Bean @ConditionalOnBean(LockService.class) public LockAspect lockAspect(LockService lockService) { return new LockAspect(lockService); } }
|
坑 1:@ConditionalOnBean / @ConditionalOnMissingBean 的判断依赖 Bean 的注册顺序。在普通 @Configuration 中使用时,被判断的 Bean 可能还没注册,结果不准确。它们应该用在自动配置类里(自动配置类在用户 Bean 之后加载),必要时配合 @AutoConfigureAfter 指定顺序。
坑 2:@ConditionalOnClass(RedisTemplate.class) 写在类上是安全的(Spring 用 ASM 读取字节码,不会加载类);写在 @Bean 方法上,如果类不存在,可能会报 ClassNotFoundException,这时改用 name = "org.springframework.data.redis.core.RedisTemplate" 字符串写法。
2.4.4 @Profile(按环境注册)
1 2 3
| spring: profiles: active: dev
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| @Configuration public class EnvConfig {
@Bean @Profile("dev") public MockPayService mockPay() { return new MockPayService(); }
@Bean @Profile({"test", "prod"}) public RealPayService realPay() { return new RealPayService(); }
@Bean @Profile("!prod") public Docket swagger() { ... } }
|
2.4.5 @ConditionalOnExpression(组合条件)
1 2 3
| @Bean @ConditionalOnExpression("${feature.sms.enabled:false} && '${spring.profiles.active}' != 'dev'") public SmsSender smsSender() { ... }
|
2.4.6 自定义 Condition
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| public class OnWindowsCondition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { String os = context.getEnvironment().getProperty("os.name", ""); return os.toLowerCase().contains("windows"); } }
@Configuration public class OsConfig { @Bean @Conditional(OnWindowsCondition.class) public FileService windowsFileService() { return new WindowsFileService(); } }
|
封装成自己的条件注解,用起来更清爽:
1 2 3 4 5 6 7 8 9
| @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Conditional(OnWindowsCondition.class) public @interface ConditionalOnWindows { }
@Bean @ConditionalOnWindows public FileService windowsFileService() { ... }
|
ConditionContext 能拿到的东西:
| 方法 |
获取内容 |
getEnvironment() |
配置项、激活的 profile |
getBeanFactory() |
已注册的 Bean |
getClassLoader() |
判断类是否存在 |
getResourceLoader() |
读取资源文件 |
调试技巧:启动时加 --debug(或配置 debug: true),控制台会打印 CONDITIONS EVALUATION REPORT,列出每个自动配置为什么生效 / 不生效。
2.5 生命周期与顺序注解
2.5.1 Bean 生命周期顺序
1 2
| 构造方法 → 依赖注入(@Autowired) → @PostConstruct → InitializingBean.afterPropertiesSet() → @Bean(initMethod) → 【使用中】 → @PreDestroy → DisposableBean.destroy() → @Bean(destroyMethod)
|
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
| @Component @Slf4j public class DictCache {
@Autowired private DictMapper dictMapper;
private Map<String, String> cache;
public DictCache() { }
@PostConstruct public void init() { cache = dictMapper.selectAll().stream() .collect(Collectors.toMap(Dict::getCode, Dict::getName)); log.info("字典缓存加载完成:{} 条", cache.size()); }
@PreDestroy public void destroy() { cache.clear(); } }
|
坑:prototype 作用域的 Bean,Spring 不管它的销毁,@PreDestroy 不会执行。
2.5.2 @DependsOn / @Order
| 注解 |
作用 |
@DependsOn("beanName") |
强制先初始化指定 Bean(没有直接注入关系但有先后要求时) |
@Order(数字) |
数字越小越先执行;影响 List 注入顺序、过滤器、切面、CommandLineRunner 等的顺序 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| @Component @DependsOn("configLoader") public class BizInitializer { }
@Component @Order(1) public class FirstRunner implements CommandLineRunner { @Override public void run(String... args) { System.out.println("启动完成后第 1 个执行"); } }
@Component @Order(2) public class SecondRunner implements ApplicationRunner { @Override public void run(ApplicationArguments args) { System.out.println("启动完成后第 2 个执行"); } }
|
坑:@Order 不能控制 Bean 的创建顺序,它只影响集合排序和执行顺序。要控制创建顺序请用 @DependsOn。
2.6 启动类与 @EnableXxx
2.6.1 @SpringBootApplication 拆解
1 2 3 4
| @SpringBootConfiguration @EnableAutoConfiguration @ComponentScan public @interface SpringBootApplication { }
|
1 2 3 4 5 6 7 8 9 10 11 12
| @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}) @MapperScan("com.demo.mapper") @EnableScheduling @EnableAsync @EnableTransactionManagement @EnableAspectJAutoProxy @EnableFeignClients public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
|
2.6.2 @EnableXxx 的原理
@EnableXxx 本质上就是一个 @Import:
1 2 3 4 5 6 7 8
| @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Import(SmsAutoConfig.class) public @interface EnableSms { }
@SpringBootApplication @EnableSms public class DemoApplication { }
|
@Import 导入的类型 |
效果 |
普通类 /@Configuration 类 |
直接注册为 Bean |
ImportSelector 实现类 |
返回一组类名,按条件批量导入(@EnableAutoConfiguration 就是这样实现的) |
ImportBeanDefinitionRegistrar 实现类 |
手动注册 BeanDefinition(@MapperScan、@EnableFeignClients 就是这样实现的) |
2.7 AOP 注解(切面)
需要引入依赖:
1 2 3 4
| <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
|
2.7.1 注解一览
| 注解 |
执行时机 |
@Aspect |
标记这个类是切面(还要加 @Component) |
@Pointcut |
定义切点表达式,供其他通知复用 |
@Before |
目标方法执行前 |
@AfterReturning |
正常返回后(能拿到返回值) |
@AfterThrowing |
抛异常后(能拿到异常) |
@After |
无论成功失败都执行(类似 finally) |
@Around |
包住整个方法,最灵活,可以决定是否执行、修改参数和返回值 |
执行顺序(Spring 5.2.7+):
1
| @Around 前半段 → @Before → 目标方法 → @AfterReturning / @AfterThrowing → @After → @Around 后半段
|
2.7.2 切点表达式
| 写法 |
含义 |
execution(* com.demo.service.*.*(..)) |
service 包下所有类的所有方法 |
execution(* com.demo.service..*.*(..)) |
service 包及子包下所有方法 |
execution(public * com.demo..*Service.get*(..)) |
以 Service 结尾的类中以 get 开头的 public 方法 |
@annotation(com.demo.annotation.Log) |
标了 @Log 注解的方法(最常用) |
within(com.demo.controller..*) |
controller 包下所有类 |
@within(org.springframework.web.bind.annotation.RestController) |
类上标了 @RestController 的所有方法 |
2.7.3 实战:自定义 @Log 注解记录操作日志
1 2 3 4 5 6
| @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Log { String value() default ""; }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| @Aspect @Component @Slf4j public class LogAspect {
@Pointcut("@annotation(com.demo.annotation.Log)") public void logPointcut() { }
@Around("logPointcut() && @annotation(logAnno)") public Object around(ProceedingJoinPoint pjp, Log logAnno) throws Throwable { long start = System.currentTimeMillis(); String method = pjp.getSignature().toShortString(); Object[] args = pjp.getArgs(); try { Object result = pjp.proceed(); log.info("[{}] {} 参数={} 耗时={}ms", logAnno.value(), method, Arrays.toString(args), System.currentTimeMillis() - start); return result; } catch (Throwable e) { log.error("[{}] {} 异常:{}", logAnno.value(), method, e.getMessage()); throw e; } } }
|
1 2 3 4 5 6
| @RestController public class UserController { @Log("新增用户") @PostMapping("/user") public R<Void> add(@RequestBody @Valid UserDTO dto) { ... } }
|
坑:AOP 基于代理实现,同一个类内部 this.xxx() 调用不会走切面(@Transactional、@Async、@Cacheable 同理,见 2.8.3)。
2.8 事务注解 @Transactional
2.8.1 常用属性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| @Service public class OrderService {
@Transactional(rollbackFor = Exception.class) public void createOrder(OrderDTO dto) { orderMapper.insert(dto); stockMapper.deduct(dto.getSkuId(), dto.getNum()); }
@Transactional(readOnly = true) public Order detail(Long id) { ... }
@Transactional(timeout = 10) public void batchImport(List<Order> list) { ... } }
|
| 属性 |
说明 |
rollbackFor |
遇到哪些异常回滚。**默认只回滚 RuntimeException 和 Error**,受检异常(如 IOException)不回滚 |
noRollbackFor |
遇到哪些异常不回滚 |
propagation |
传播行为(见下表) |
isolation |
隔离级别,默认跟随数据库(MySQL 是可重复读) |
readOnly |
只读 |
timeout |
超时时间(秒) |
2.8.2 传播行为
| 传播行为 |
当前有事务 |
当前没有事务 |
场景 |
REQUIRED(默认) |
加入 |
新建 |
绝大多数场景 |
REQUIRES_NEW |
挂起当前事务,新建独立事务 |
新建 |
记录日志:主业务回滚,日志仍要保存 |
NESTED |
嵌套事务(保存点),子事务回滚不影响外层 |
新建 |
部分步骤允许失败 |
SUPPORTS |
加入 |
以非事务方式执行 |
查询 |
NOT_SUPPORTED |
挂起,以非事务方式执行 |
非事务执行 |
— |
MANDATORY |
加入 |
抛异常 |
必须在事务里被调用 |
NEVER |
抛异常 |
非事务执行 |
— |
1 2 3 4 5
| @Service public class LogService { @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class) public void saveLog(String msg) { ... } }
|
2.8.3 事务失效的常见场景
| 场景 |
原因 |
解决 |
方法不是 public |
代理只拦截 public 方法 |
改成 public |
同类内部 this.b() 调用 |
没有经过代理对象 |
拆到另一个 Bean;或注入自己 /AopContext.currentProxy() |
异常被 try-catch 吞掉 |
事务管理器感知不到异常 |
重新抛出,或调用 TransactionAspectSupport.currentTransactionStatus().setRollbackOnly() |
| 抛的是受检异常 |
默认只回滚运行时异常 |
加 rollbackFor = Exception.class |
| 类没有交给 Spring 管理 |
自己 new 的对象没有代理 |
用注入的 Bean |
方法是 final / static |
CGLIB 无法重写 |
去掉修饰符 |
| 在新线程里操作数据库 |
事务绑定在当前线程(ThreadLocal) |
不要跨线程,或在子线程中单独开事务 |
| 数据库引擎不支持事务 |
如 MySQL 的 MyISAM |
改用 InnoDB |
1 2 3 4 5 6 7 8 9 10
| @Service public class OrderService {
public void submit(OrderDTO dto) { this.createOrder(dto); }
@Transactional(rollbackFor = Exception.class) public void createOrder(OrderDTO dto) { ... } }
|
2.9 异步与定时注解
2.9.1 @Async
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| @Configuration @EnableAsync public class AsyncConfig {
@Bean("bizExecutor") public ThreadPoolTaskExecutor bizExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(8); executor.setMaxPoolSize(16); executor.setQueueCapacity(200); executor.setThreadNamePrefix("biz-async-"); executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); executor.initialize(); return executor; } }
|
1 2 3 4 5 6 7 8 9 10 11
| @Service public class NoticeService {
@Async("bizExecutor") public void sendMail(String to) { ... }
@Async("bizExecutor") public CompletableFuture<String> query(Long id) { return CompletableFuture.completedFuture("ok"); } }
|
坑:@Async 失效的原因与事务一样(同类调用、非 public);另外异步方法里抛的异常调用方感知不到,需要实现 AsyncUncaughtExceptionHandler 统一处理。
2.9.2 @Scheduled
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| @Component @EnableScheduling public class ReportJob {
@Scheduled(cron = "0 0 2 * * ?") public void dailyReport() { ... }
@Scheduled(fixedRate = 5000) public void heartbeat() { ... }
@Scheduled(fixedDelay = 5000, initialDelay = 10000) public void sync() { ... }
@Scheduled(cron = "${job.clean.cron:0 0/30 * * * ?}") public void clean() { ... } }
|
cron 格式(6 位):秒 分 时 日 月 周
| 示例 |
含义 |
0 0/5 * * * ? |
每 5 分钟 |
0 0 9-18 * * MON-FRI |
工作日 9 点到 18 点,每个整点 |
0 0 0 1 * ? |
每月 1 号 0 点 |
0 0 23 L * ? |
每月最后一天 23 点 |
坑:默认所有定时任务共用一个线程,一个任务卡住会导致其他任务都不执行。需要配置 spring.task.scheduling.pool.size: 5。另外部署多个实例时每个实例都会执行,需要分布式锁(如 ShedLock)或改用 XXL-JOB。
2.10 其他常用注解
2.10.1 缓存注解
需要在启动类上加 @EnableCaching。
| 注解 |
作用 |
@Cacheable |
先查缓存,命中直接返回;没命中再执行方法,并把结果写入缓存 |
@CachePut |
每次都执行方法,并用结果更新缓存 |
@CacheEvict |
删除缓存 |
@Caching |
组合多个缓存操作 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| @Service public class UserService {
@Cacheable(value = "user", key = "#id", unless = "#result == null") public User getById(Long id) { ... }
@CachePut(value = "user", key = "#user.id") public User update(User user) { ... }
@CacheEvict(value = "user", key = "#id") public void delete(Long id) { ... }
@CacheEvict(value = "user", allEntries = true) public void clearAll() { } }
|
2.10.2 事件注解
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
| public record UserRegisteredEvent(Long userId, String email) { }
@Service @RequiredArgsConstructor public class UserService { private final ApplicationEventPublisher publisher;
@Transactional(rollbackFor = Exception.class) public void register(UserDTO dto) { publisher.publishEvent(new UserRegisteredEvent(1L, dto.getEmail())); } }
@Component public class UserEventListener {
@EventListener public void onRegister(UserRegisteredEvent e) { ... }
@Async @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) public void sendWelcomeMail(UserRegisteredEvent e) { ... } }
|
场景:注册成功后发邮件、送积分,用事件解耦,主流程不依赖这些附属逻辑。用 AFTER_COMMIT 可以避免”事务回滚了,邮件却发出去了”。
2.10.3 Lombok 常用注解
| 注解 |
生成内容 |
@Getter / @Setter |
getter / setter |
@ToString |
toString(),可用 exclude 排除字段 |
@EqualsAndHashCode |
equals() / hashCode() |
@Data |
=@Getter + @Setter + @ToString + @EqualsAndHashCode + @RequiredArgsConstructor |
@NoArgsConstructor |
无参构造 |
@AllArgsConstructor |
全参构造 |
@RequiredArgsConstructor |
为 final 字段和 @NonNull 字段生成构造器(配合构造器注入) |
@Builder |
建造者模式:User.builder().name("a").build() |
@Slf4j |
生成 private static final Logger log |
@Accessors(chain = true) |
setter 返回 this,支持链式调用 |
@SneakyThrows |
不用声明就能抛出受检异常 |
@Value(Lombok 的) |
不可变类:字段都是 private final,只有 getter |
坑 1:@Data 用在有继承关系的类上时,equals 默认不比较父类字段,需要加 @EqualsAndHashCode(callSuper = true)。
坑 2:只加 @Builder 时会丢失无参构造,Jackson 反序列化、MyBatis 映射会失败,需要同时加 @NoArgsConstructor + @AllArgsConstructor。
坑 3:Lombok 的 @Value 和 Spring 的 @Value 同名,注意 import 的包(lombok.Value 和 org.springframework.beans.factory.annotation.Value)。
2.11 元注解(自定义注解时用)
| 元注解 |
作用 |
常用值 |
@Target |
注解能用在哪里 |
TYPE(类)、METHOD、FIELD、PARAMETER |
@Retention |
注解保留到什么时候 |
SOURCE(编译后丢弃,如 Lombok)、CLASS、**RUNTIME(运行时可以反射读取,Spring 场景必须用这个)** |
@Documented |
生成到 javadoc 中 |
— |
@Inherited |
子类继承父类上的注解(只对类有效) |
— |
@Repeatable |
同一位置可以重复使用 |
— |
Spring 的组合注解:注解上可以再加注解,Spring 会递归识别。
1 2 3 4 5 6 7 8
| @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @RestController @RequestMapping("/api/v1") public @interface ApiV1Controller { }
@ApiV1Controller public class OrderController { }
|
@AliasFor 让组合注解的属性透传给被组合的注解:
1 2 3 4 5 6 7
| @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Service public @interface BizService { @AliasFor(annotation = Service.class, attribute = "value") String value() default ""; }
|
2.12 注解速查表
| 分类 |
注解 |
| 组件注册 |
@Component @Service @Repository @Controller @RestController @Configuration @Bean |
| 扫描导入 |
@ComponentScan @Import @ImportResource @MapperScan |
| 作用域 |
@Scope @Lazy @Primary |
| 依赖注入 |
@Autowired @Qualifier @Resource @Value |
| 配置属性 |
@ConfigurationProperties @EnableConfigurationProperties @PropertySource |
| 条件 |
@Conditional @ConditionalOnProperty @ConditionalOnClass @ConditionalOnMissingClass @ConditionalOnBean @ConditionalOnMissingBean @ConditionalOnWebApplication @ConditionalOnExpression @Profile |
| 生命周期 |
@PostConstruct @PreDestroy @DependsOn @Order |
| 启动 / 开关 |
@SpringBootApplication @EnableAutoConfiguration @EnableAsync @EnableScheduling @EnableCaching @EnableTransactionManagement |
| Web |
@RequestMapping @GetMapping @PostMapping @RequestParam @PathVariable @RequestBody @RequestHeader @ResponseBody(详见第一章) |
| 校验 |
@Valid @Validated @NotNull @NotBlank @Size @Pattern(详见 1.5) |
| 异常 |
@RestControllerAdvice @ExceptionHandler(详见 1.7) |
| AOP |
@Aspect @Pointcut @Before @After @AfterReturning @AfterThrowing @Around |
| 事务 |
@Transactional |
| 异步定时 |
@Async @Scheduled |
| 缓存 |
@Cacheable @CachePut @CacheEvict |
| 事件 |
@EventListener @TransactionalEventListener |
2.13 常见坑汇总
| 现象 |
原因 |
解决 |
No qualifying bean of type xxx |
类不在扫描路径下 / 忘了加组件注解 / 条件注解不成立 |
检查包路径;用 --debug 查看条件评估报告 |
expected single matching bean but found 2 |
同一类型有多个实现 |
@Qualifier / @Primary / @Resource(name) |
@Value 注入为 null |
静态字段 / 对象是自己 new 的 / 在构造方法中使用 |
改为非静态;用注入的 Bean;放到 @PostConstruct 中使用 |
The dependencies of some of the beans form a cycle |
循环依赖 |
拆分逻辑;临时在一侧加 @Lazy |
@Transactional / @Async / @Cacheable 不生效 |
同类内部调用、非 public、异常被吞 |
见 2.8.3 |
@ConditionalOnMissingBean 判断错误 |
用在普通配置类中,Bean 注册顺序不确定 |
只在自动配置类中使用 |
| 自定义注解在切面中读不到 |
@Retention 不是 RUNTIME |
改为 RetentionPolicy.RUNTIME |
| 定时任务互相阻塞 |
默认单线程 |
配置 spring.task.scheduling.pool.size |
@Configuration 中 @Bean 方法互相调用产生了多个实例 |
用了 proxyBeanMethods = false 或 @Component |
改为通过方法参数注入 |