Spring RestController使用@RequestBody时POST请求返回400错误求助
问题原因及解决方案
1. Product类缺少无参构造方法
Spring通过Jackson处理JSON反序列化时,默认需要无参构造方法来实例化对象,再通过setter为属性赋值。你的Product类仅定义了全参构造方法,导致Jackson无法创建Product实例,触发400 Bad Request。
2. ProductController构造方法为private
Spring需要实例化Controller Bean来处理请求,私有构造方法会导致Spring无法通过反射创建ProductController实例,即使GET请求暂时可用,也存在Bean初始化的潜在问题。
3. 需确保getter/setter方法完整
虽然你提到已省略,但必须保证所有属性的getter和setter方法存在且正确实现,Jackson依赖这些方法完成属性的读写操作。
修改后的代码示例
Product类
public class Product { private int productId; private String name; private double price; private String description; // 添加无参构造方法 public Product() { } // 全参构造方法 public Product(int productId, String name, double price, String description) { this.productId = productId; this.name = name; this.price = price; this.description = description; } // 完整的getter和setter public int getProductId() { return productId; } public void setProductId(int productId) { this.productId = productId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
ProductController类
@RestController @RequestMapping("/v1") public class ProductController { private ProductRepository productRepo; // 改为public构造方法,支持Spring构造注入 public ProductController(ProductRepository productRepo) { this.productRepo = productRepo; } @GetMapping("/products") public List<Product> getProduct() { return productRepo.findAllProducts(); } @PostMapping("/products") public List<Product> postProduct(@RequestBody Product product) { return productRepo.saveProduct(product); } }
内容的提问来源于stack exchange,提问作者RyanKao
相关产品推荐
相关产品推荐

