javaSpring
邵预鸿 Lv5

一、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>
<!-- Web:内置 Tomcat + SpringMVC + Jackson(JSON 序列化) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- 参数校验:@Valid / @NotBlank / @NotNull 等 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>

<!-- Lombok:省掉 getter/setter/构造器 -->
<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                 // = @Controller + @ResponseBody(返回值直接写 JSON)
@RequestMapping("/api/users") // 类级别公共路径
public class UserController {

// GET http://localhost:8080/api/users/1
@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 {

// 仅当存在 type=app 参数时才匹配:GET /api/orders/search?type=app
@GetMapping(value = "/search", params = "type=app")
public List<OrderVO> searchFromApp(@RequestParam String keyword) {
return orderService.search(keyword);
}

// 仅当 Content-Type=application/json 时才匹配
@PostMapping(value = "/create", consumes = "application/json")
public R<Long> create(@RequestBody OrderCreateDTO dto) {
return R.ok(orderService.create(dto));
}

// 指定响应类型(解决部分老浏览器 JSON 被当文件下载)
@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 {

/**
* GET /api/raw/user?id=1
* 完全不用 @RequestParam,自己从 request 里取
*/
@GetMapping("/user")
public void getUser(HttpServletRequest request,
HttpServletResponse response) throws IOException {

// 1. 取参数(Spring 的 @RequestParam 底层就是它)
String idStr = request.getParameter("id");

// 2. 手动做类型转换(Spring 的 Converter 帮你做了)
Long id = Long.valueOf(idStr);

// 3. 业务处理
UserVO user = userService.getById(id);

// 4. 手动设置响应(Spring 的 @ResponseBody 帮你做了)
response.setStatus(HttpServletResponse.SC_OK); // 200
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(JSON.toJSONString(R.ok(user)));
}

/**
* POST /api/raw/create
* Body: {"username":"zhangsan","age":25}
* 手动读请求体,等价于 @RequestBody
*/
@PostMapping("/create")
public void createUser(HttpServletRequest request,
HttpServletResponse response) throws IOException {

// 读请求体原始 JSON(注意:只能读一次!@RequestBody 读完后这里再读就是空)
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); // 201
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 优先用注解,原生对象只在以下场景兜底:

  1. 文件下载 / 验证码 / 图片:需要直接操作 response.getOutputStream()
  2. 写 Cookie:response.addCookie(new Cookie("token", token))
  3. 拦截器与 Controller 传值:request.setAttribute("userId", 1L) → Controller 里 request.getAttribute("userId")
  4. 获取真实 IP:经过 Nginx 代理时要读 X-Forwarded-For 头
  5. 接口验签:需要读取原始请求体做签名比对(此时不能用 @RequestBody,否则流已被消费)
  6. 导出 Excel / CSV:直接写输出流,避免大文件撑爆内存

1.3.7 两个必知的坑

1
2
3
4
5
6
7
8
// 坑 1:请求体只能读一次
// @RequestBody 读过之后,request.getReader() 再读就是空字符串
// 解决:用 ContentCachingRequestWrapper 包装 request(配合 Filter 使用)

// 坑 2:getWriter() 和 getOutputStream() 二选一,不能同时用
// IllegalStateException: getWriter() has already been called
response.getWriter().write("xxx");
// response.getOutputStream().write(bytes); // 报错!

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
// GET /api/users/100
@GetMapping("/{id}")
public R<UserVO> getById(@PathVariable("id") Long id) {
return R.ok(userService.getById(id));
}

// 参数名与占位符一致时,可省略 ("id")
@GetMapping("/{id}")
public R<UserVO> getById(@PathVariable Long id) { ... }

// 多个路径参数:GET /api/users/100/orders/2024
@GetMapping("/{userId}/orders/{year}")
public R<List<OrderVO>> userOrders(@PathVariable Long userId,
@PathVariable Integer year) {
return R.ok(orderService.listByUserAndYear(userId, year));
}

// Map 一次性接全部:/api/dept/10/user/20
@GetMapping("/dept/{deptId}/user/{userId}")
public R<Map<String, String>> test(@PathVariable Map<String, String> pathVars) {
// pathVars = {deptId=10, userId=20}
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
// GET /api/users?page=1&size=10
@GetMapping("url")
public R<List<UserVO>> list(@RequestParam(defaultValue = "1") Integer page,
@RequestParam(defaultValue = "10") Integer size) {
return R.ok(userService.page(page, size));
}

// 参数封装为对象
// User是引入的封装对象类 user->接收的参数名
// 如 ?name=xiaoming&age=22
@GetMapping("url")
public void list(User user) {
/**
user: {name: xiaoming, age: 22}
**/
}

// 默认为普通数组, 当参数需要转为复杂对象时如List,使用注释
// User是引入的封装对象类 user->接收的参数名 见-----------------> 1.4.6
// 如 ?name=xiaoming&name=xiaohong
@GetMapping("url")
public void list(@RequestParam List<String> list) {

}


// 当前端传的name , 后端要改为userName时?
// User是引入的封装对象类 user->接收的参数名
@GetMapping("url")
public void list(@RequestParam(name="name") String userName) {

}

// required = false:参数可选,不传为 null
// GET /api/users/search?keyword=张
@GetMapping("/search")
public R<List<UserVO>> search(@RequestParam(required = false) String keyword) {
return R.ok(userService.search(keyword));
}


// 时间类, 前端传yyyy-mm-dd HH:mm:ss 见----------------> 1.4.7
// 如 /url?date=yyyy-mm-dd HH:mm:ss
@GetMapping("url")
public void list(@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") LocalDataTime ldt) {
ldt->就是LocalDataTime的日期类型
}


// 前端post请求传json类 见 --------> 1.4.3 @RequestBody JSON 请求体
@GetMapping("url")
public void list(@RequestBody User user) {

}


// 路径参数
// 如/set/xiaoming
@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;
}

// POST /api/users
// Content-Type: application/json
// {"username":"zhangsan","password":"123456","email":"zs@test.com","age":25}
@PostMapping
public R<Long> create(@RequestBody UserCreateDTO dto) {
return R.ok(userService.create(dto));
}

规则:

  1. 一个方法只能有一个 @RequestBody
  2. 前端必须带 Content-Type: application/json,否则报 415
  3. 接收数组:@RequestBody List<Long> ids
1
2
3
4
5
6
// POST /api/users/batch-delete   Body: [1,2,3]
@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;
}

// GET /api/users/list?keyword=张&status=1&page=1&size=10
// 或 application/x-www-form-urlencoded 表单提交,效果一样
@GetMapping("/list")
public R<List<UserVO>> list(UserQueryDTO query) {
return R.ok(userService.list(query));
}

Spring 会把请求参数按属性名自动塞进对象。这是最省事的写法,查询类接口优先用它。

1.4.5 @RequestHeader / @CookieValue

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);
}

// 取 Cookie
@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
// GET /api/users/ids?ids=1&ids=2&ids=3
@GetMapping("/ids")
public R<List<UserVO>> byIds(@RequestParam List<Long> ids) {
return R.ok(userService.listByIds(ids));
}

// GET /api/users/ids2?ids=1,2,3 (逗号分隔,自动转数组)
@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 {
// 前端传 "2026-10-15" 才能绑定成功,否则 400
@DateTimeFormat(pattern = "yyyy-MM-dd")
private LocalDate startDate;

// 前端传 "2026-10-15 14:30:00"
@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 {

// 单文件:POST /api/files/upload (form-data: key=file)
@PostMapping("/upload")
public R<String> upload(@RequestParam("file") MultipartFile file) throws IOException {
if (file.isEmpty()) {
return R.fail("文件为空");
}

String originalName = file.getOriginalFilename(); // a.jpg
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(); // GET
String uri = request.getRequestURI(); // /api/users/raw
String ip = request.getRemoteAddr(); // 客户端 IP
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\"}");
}

// 取真实 IP(经过 Nginx 代理时)
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();
}
// X-Forwarded-For 可能是 "client, proxy1, proxy2"
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 才会级联校验
@Valid
@NotNull(message = "地址不能为空")
private AddressDTO address;
}

@Data
public class AddressDTO {
@NotBlank(message = "城市不能为空")
private String city;
}

// Controller:@RequestBody 前加 @Valid 或 @Validated
@PostMapping
public R<Long> create(@Valid @RequestBody UserCreateDTO dto) {
return R.ok(userService.create(dto));
}

// 非 JSON 的对象绑定用 @Validated
@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);
}
// 响应:{"id":1,"name":"张三","age":25,"createTime":"2026-10-15 10:30:00"}

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); // 201
}

// 自定义响应头 + 下载文件
@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(); // 204
}

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; // 0=成功,其他=失败
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) {
// 已经是 R 类型、或返回 void/String(如文件下载),不重复包装
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) {
// String 类型要用 StringHttpMessageConverter,必须手动转 JSON
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); // 自动包装成 {"code":0,"data":{...}}
}

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   // = @ControllerAdvice + @ResponseBody
@Slf4j
public class GlobalExceptionHandler {

/** 参数校验失败(@Valid) */
@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);
}

/** 单参数校验失败(@Validated 直接标在参数上) */
@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);
}

/** 参数类型错误:/users/abc 传给 Long id */
@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());
}

/** JSON 格式错误 */
@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 {

/** Controller 方法执行前 */
@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; // false = 中断请求
}
// 把用户信息放进 request,Controller 里可取
request.setAttribute("userId", TokenUtil.getUserId(token));
return true;
}

/** Controller 方法执行后、视图渲染前 */
@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("*") // Spring Boot 2.4+ 支持通配符+凭证
.allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")
.allowedHeaders("*")
.exposedHeaders("Authorization", "Content-Disposition") // 前端能读到的响应头
.allowCredentials(true)
.maxAge(3600); // 预检请求缓存 1 小时
}
}

方案二:单接口注解

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 {

// 重命名:Java 是 userName,JSON 是 user_name
@JsonProperty("user_name")
private String userName;

// 不返回给前端(密码、盐值等)
@JsonIgnore
private String password;

// null 不返回(也可全局配置)
@JsonInclude(JsonInclude.Include.NON_NULL)
private String remark;

// 日期格式化
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private LocalDateTime createTime;

// 数字保留 2 位:1234.567 → "1234.57"
@JsonSerialize(using = BigDecimalSerializer.class)
private BigDecimal amount;

// 枚举返回描述而非名称:{"code":1,"desc":"启用"}
@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 # 全局 null 字段不返回
deserialization:
fail-on-unknown-properties: false # JSON 有多余字段时不报错

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 -> {
// Long / 大整数 → String,避免前端精度丢失
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;

/** 分页查询:GET /api/users?page=1&size=10&keyword=张 */
@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));
}

/** 详情:GET /api/users/1 */
@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);
}

/** 新增:POST /api/users */
@PostMapping
public R<Long> create(@Valid @RequestBody UserCreateDTO dto) {
return R.ok(userService.create(dto));
}

/** 全量更新:PUT /api/users/1 */
@PutMapping("/{id}")
public R<Void> update(@PathVariable Long id,
@Valid @RequestBody UserUpdateDTO dto) {
userService.update(id, dto);
return R.ok();
}

/** 局部改状态:PATCH /api/users/1/status?status=1 */
@PatchMapping("/{id}/status")
public R<Void> updateStatus(@PathVariable Long id,
@RequestParam Integer status) {
userService.updateStatus(id, status);
return R.ok();
}

/** 删除:DELETE /api/users/1 */
@DeleteMapping("/{id}")
public R<Void> delete(@PathVariable Long id) {
userService.removeById(id);
return R.ok();
}

/** 批量删除:POST /api/users/batch-delete Body: [1,2,3] */
@PostMapping("/batch-delete")
public R<Void> batchDelete(@RequestBody List<Long> ids) {
userService.removeByIds(ids);
return R.ok();
}

/** 导出:GET /api/users/export */
@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; // Long 转 String,防精度丢失
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                       // 默认 Bean 名 = 类名首字母小写:smsSender
public class SmsSender { }

@Service("userService") // 手动指定 Bean 名
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 {

// Bean 名默认 = 方法名:restTemplate
@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()); // @Configuration 下拿到的是容器里那个 a;换成 @Component 就是新 new 的
}
}

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 // 有两个 DataSource 时,不写 @Qualifier 就注入 master
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; // 注入所有实现:key=Bean名,value=实例(策略模式常用)

@Autowired
private List<PayService> payList; // 注入所有实现,顺序受 @Order 控制

@Autowired(required = false) // 容器里没有也不报错,值为 null
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 // Lombok:为所有 final 字段生成构造器 → 自动构造器注入
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}") // 逗号分隔自动转数组/List
private List<String> whiteList;

@Value("#{${app.timeout} * 2}") // #{} 是 SpEL 表达式,可以计算
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 // 方式一:直接加 @Component
@ConfigurationProperties(prefix = "sms")
public class SmsProperties {
private Boolean enabled;
private String accessKey; // access-key 自动映射为驼峰(宽松绑定)
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
// 方式二:属性类不加 @Component,在配置类上启用(写 starter 时常用)
@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 {

// feature.sms.enabled=true 才注册
@Bean
@ConditionalOnProperty(prefix = "feature.sms", name = "enabled", havingValue = "true")
public SmsSender smsSender() {
return new AliyunSmsSender();
}

// matchIfMissing = true:没配置这个项时也当作成立(默认开启)
@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) // 引入了 spring-data-redis 才处理
@EnableConfigurationProperties(LockProperties.class)
public class DistributedLockAutoConfig {

@Bean
@ConditionalOnMissingBean // 用户自己定义了 LockService 就用用户的
public LockService lockService(RedisTemplate<String, Object> redisTemplate) {
return new RedisLockService(redisTemplate);
}

@Bean
@ConditionalOnBean(LockService.class) // 有 LockService 才注册切面
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 # 也可以启动时传:--spring.profiles.active=prod
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") // 非生产环境才开启 Swagger
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
/** 当前操作系统是 Windows 时成立 */
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() {
// 这里 dictMapper 还是 null,不能用!
}

@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") // 保证 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      // 本质是 @Configuration,启动类本身就是一个配置类
@EnableAutoConfiguration // 开启自动配置:读取 META-INF/spring/...AutoConfiguration.imports 中的配置类
@ComponentScan // 扫描启动类所在包及其子包
public @interface SpringBootApplication { }
1
2
3
4
5
6
7
8
9
10
11
12
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})  // 排除某个自动配置(如暂时不连数据库)
@MapperScan("com.demo.mapper") // MyBatis:扫描 Mapper 接口
@EnableScheduling // 开启定时任务
@EnableAsync // 开启异步
@EnableTransactionManagement // 开启事务(Spring Boot 默认已开启,可省略)
@EnableAspectJAutoProxy // 开启 AOP(Spring Boot 默认已开启,可省略)
@EnableFeignClients // OpenFeign:扫描 @FeignClient 接口
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) // 加上这个注解 = 导入 SmsAutoConfig
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) // 必须是 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) // 强烈建议每次都写 rollbackFor
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); // 失效!this 是原始对象,不是代理
}

@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 {

// 自定义线程池。不配置的话,Spring Boot 2.1+ 会使用默认的 ThreadPoolTaskExecutor(队列无界)
@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) { // 需要返回值时用 CompletableFuture
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 * * ?") // 每天凌晨 2 点
public void dailyReport() { ... }

@Scheduled(fixedRate = 5000) // 每 5 秒一次(从上次开始时间算)
public void heartbeat() { ... }

@Scheduled(fixedDelay = 5000, initialDelay = 10000) // 上次结束后 5 秒再执行;启动 10 秒后第一次执行
public void sync() { ... }

@Scheduled(cron = "${job.clean.cron:0 0/30 * * * ?}") // cron 从配置读取
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) // 清空整个 user 缓存
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
// 1. 定义事件
public record UserRegisteredEvent(Long userId, String email) { }

// 2. 发布事件
@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()));
}
}

// 3. 监听事件
@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 { } // 一个注解 = @RestController + 统一前缀

@ApiV1Controller
public class OrderController { } // 接口前缀自动为 /api/v1

@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 ""; // @BizService("xxx") 等同于 @Service("xxx")
}

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 改为通过方法参数注入
  • 本文标题:javaSpring
  • 本文作者:邵预鸿
  • 创建时间:2026-10-15 18:33:20
  • 本文链接:/images/logo.jpg2026/10/15/javaSpring/
  • 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!