Spring Boot中@RequestBody接收对象保存MongoDB前如何设置未传属性
解决方案:为非RequestBody传入的Customer实体属性赋值
核心问题定位
你当前的赋值代码不生效是两个低级错误直接导致的:
- 实体类
Customer被错误添加了@Configuration注解:该注解是用来标记Spring配置类的,会让Spring将Customer实例化为单例Bean,直接干扰@RequestBody的参数绑定逻辑 - Controller导包错误:你定义的实体类路径是
com.example.customerapi.model.Customer,但Controller中导入的是com.example.model.Customer,二者不是同一个类,你设置type的操作是作用在错误的类对象上,自然不会生效
修复步骤
第一步:删除实体类的错误注解
去掉Customer类上的@Configuration注解,修改后的类注解如下:
@Getter @Setter @ToString @Document(collection = "customer") @JsonInclude(Include.NON_NULL) public class Customer implements Serializable { // 原有属性保持不变 }
第二步:修正Controller的导包
将Controller中错误的Customer导入替换为正确的实体类路径:
// 删掉错误导包 import com.example.model.Customer; import com.example.customerapi.model.Customer;
完成以上两步后,你现有代码里的customer.setType("test_type")就可以正常生效了。
可选优化方案
防止前端传入type字段覆盖后端赋值
如果要完全禁止前端传入的type参数覆盖后端设置的值,可以给type字段加@JsonProperty的access属性限制反序列化:
@Field("type") @JsonProperty(access = JsonProperty.Access.READ_ONLY) // 只在序列化返回给前端时生效,反序列化时忽略前端传值 private String type;
全局自动赋值(适合多接口复用场景)
如果多个接口保存Customer都需要设置type,可以使用Spring Data MongoDB的生命周期监听实现全局自动赋值,无需每个接口手动set:
- 新建事件监听类
package com.example.customerapi.listener; import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener; import org.springframework.data.mongodb.core.mapping.event.BeforeSaveEvent; import org.springframework.stereotype.Component; import com.example.customerapi.model.Customer; @Component public class CustomerSaveListener extends AbstractMongoEventListener<Customer> { @Override public void onBeforeSave(BeforeSaveEvent<Customer> event) { Customer customer = event.getSource(); // 统一设置type值 customer.setType("test_type"); } }
- 接口中无需再手动调用
setType方法,保存时会自动注入值。
内容的提问来源于stack exchange,提问作者Valay
相关产品推荐
相关产品推荐

