Spring MVC中使用嵌套Java Record抛出异常,求解决方案
Spring MVC嵌套Java Record使用报错的解决方法
问题说明
当在Spring MVC中使用嵌套Java Record作为@ModelAttribute接收POST请求时,出现如下异常:
org.springframework.beans.NullValueInNestedPathException
Could not instantiate property type RankDto to auto-grow nested property path
涉及代码如下:
嵌套Record定义
public record RankDto(String rank, long rankNumber) {} public record WorkersDto(String firstName, RankDto rankDto) {}
Controller接口
@RequestMapping(value = "/edit", method = RequestMethod.POST) public String edit(@ModelAttribute("worker") WorkersDto workersDto){ return userService.edit(workersDto); }
这是Spring Framework的已知兼容性问题,以下是几种可行的解决方式:
解决方法
1. 改用@RequestBody接收JSON请求
如果前端发送的是JSON格式请求体,将@ModelAttribute替换为@RequestBody。Spring的JSON序列化器(如Jackson)可以直接处理嵌套Record的反序列化,无需依赖Spring的属性自动填充逻辑:
@RequestMapping(value = "/edit", method = RequestMethod.POST) public String edit(@RequestBody WorkersDto workersDto){ return userService.edit(workersDto); }
2. 自定义PropertyEditor适配表单请求
如果必须使用表单提交(application/x-www-form-urlencoded),可以通过@InitBinder注册自定义PropertyEditor,手动处理嵌套Record的实例化:
@Controller public class WorkerController { @InitBinder public void initBinder(WebDataBinder binder) { binder.registerCustomEditor(RankDto.class, new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { // 根据实际表单参数格式调整解析逻辑,示例按逗号拆分参数 String[] parts = text.split(","); if (parts.length == 2) { setValue(new RankDto(parts[0], Long.parseLong(parts[1]))); } } }); } @RequestMapping(value = "/edit", method = RequestMethod.POST) public String edit(@ModelAttribute("worker") WorkersDto workersDto){ return userService.edit(workersDto); } }
3. 升级Spring Framework版本
该问题已在Spring Framework 6.0.13及后续版本(对应Spring Boot 3.1.4+)中修复,若项目允许升级框架,直接更新到修复后的版本即可,无需修改业务代码。
内容的提问来源于stack exchange,提问作者Thomas Lang
相关产品推荐
相关产品推荐

