一文讲透一个Spring Boot装饰器 - @RequestBody

在 Spring Boot 开发中,@RequestBody 是一个非常常用但容易被误解的注解。本文将从原理到实践,全面解析它的作用、使用方式、底层机制以及常见坑点,帮助你彻底掌握它。

一、什么是 @RequestBody?

@RequestBody 是 Spring MVC 提供的注解之一,用于将 HTTP 请求体中的 JSON/XML 数据绑定到 Java 对象上。

基本定义:

@Target(ElementType.PARAMETER)

@Retention(RetentionPolicy.RUNTIME)

@Documented

public @interface RequestBody {

boolean required() default true;

}

它只能用于方法参数上,不能用于类或字段。

二、使用场景

在 RESTful 接口中,前端通常通过 POST/PUT 请求发送 JSON 数据,后端需要通过 @RequestBody 将其转换为 Java 对象。

示例:

@PostMapping("/user")

public ResponseEntity createUser(@RequestBody User user) {

// 处理 user 对象

return ResponseEntity.ok("User created");

}

请求体如下:

{

"name": "Alice",

"age": 25

}

Spring 会自动将 JSON 转换为 User 对象。

三、底层原理

Spring 使用 HttpMessageConverter 来处理请求体的转换。

流程如下:

请求到达 DispatcherServlet。HandlerMapping 找到对应的 Controller 方法。RequestResponseBodyMethodProcessor 处理 @RequestBody 参数。使用 MappingJackson2HttpMessageConverter 将 JSON 转换为 Java 对象。

默认使用 Jackson 进行 JSON 解析。

四、常见错误及解决方案

1. 请求体为空或格式错误

错误信息:

Required request body is missing

原因:

请求体为空。Content-Type 不是 application/json。

解决:

确保请求体不为空。设置正确的 Content-Type。

2. JSON 字段与 Java 对象不匹配

错误信息:

Unrecognized field "xxx" (class com.example.User), not marked as ignorable

解决:

在类上添加注解忽略未知字段:

@JsonIgnoreProperties(ignoreUnknown = true)

public class User {

...

}

3. 请求体过大

错误信息:

Request body is too large

解决:

在配置文件中设置:

spring:

servlet:

multipart:

max-request-size: 10MB

五、进阶技巧

1. 自定义转换器

可以实现 HttpMessageConverter 接口,注册自定义的消息转换器。

@Configuration

public class WebConfig implements WebMvcConfigurer {

@Override

public void configureMessageConverters(List> converters) {

converters.add(new MyCustomConverter());

}

}

2. 参数校验

结合 @Valid 注解,可以对请求体进行校验。

@PostMapping("/user")

public ResponseEntity createUser(@Valid @RequestBody User user) {

return ResponseEntity.ok("Valid user");

}

public class User {

@NotBlank

private String name;

@Min(18)

private int age;

}

六、总结

特性描述注解位置方法参数作用将请求体绑定到 Java 对象支持格式JSON、XML(需配置)常见错误空请求体、字段不匹配、格式错误最佳实践使用 @Valid 校验、设置 Content-Type、处理异常

七、参考文档

Spring Boot 官方文档Jackson 官方文档