You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot控制器如何接收多个@RequestBody并按类型分别保存

问题根因

Spring MVC 中单个HTTP请求的请求体是仅可读取一次的流,因此@RequestBody注解在同一个接口方法中只能使用一次,无法同时将请求体绑定到两个不同的实体类对象,你原来的写法会直接抛出请求读取异常。

最佳实现方案

通过自定义统一请求DTO(数据传输对象)包装两个实体类,是类型安全、可维护性最高的实现方式。

  1. 定义统一请求包装类
public class SavePersonHumanRequest {
    // 嵌套两个需要接收的实体对象
    private Person person;
    private Human human;

    // 必须添加Getter/Setter方法,Spring完成JSON反序列化依赖这些方法
    public Person getPerson() {
        return person;
    }

    public void setPerson(Person person) {
        this.person = person;
    }

    public Human getHuman() {
        return human;
    }

    public void setHuman(Human human) {
        this.human = human;
    }
}
  1. 调整控制器接口逻辑
@PostMapping(value="/save")
public void saveTwoObjects(@RequestBody SavePersonHumanRequest request) {
    personRepo.save(request.getPerson());
    humanRepo.save(request.getHuman());          
}
  1. 前端请求传入的JSON格式示例
{
  "person": {
    "a": 1,
    "b": 2,
    "c": 3
  },
  "human": {
    "a": 4,
    "b": 5,
    "c": 6
  }
}
注意事项

你给出的Human类代码中,int c末尾缺少分号,需要修正避免编译报错。

可选简化方案(不推荐生产使用)

如果不想额外创建DTO类,可以直接用Map接收后手动转换,缺点是丢失编译期类型校验:

@PostMapping(value="/save")
public void saveTwoObjects(@RequestBody Map<String, Object> requestMap) {
    ObjectMapper mapper = new ObjectMapper();
    Person person = mapper.convertValue(requestMap.get("person"), Person.class);
    Human human = mapper.convertValue(requestMap.get("human"), Human.class);
    personRepo.save(person);
    humanRepo.save(human);
}

内容的提问来源于stack exchange,提问作者bijay limbu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 17:45:05