使用 Spring 4,我有一个用例,其中资源(下例中的 A)具有在使用 REST 更新(http put 和 patch)时应该被忽略的属性。该属性只能在创建时具有值(http post)。所以情况是create上的解组应该考虑该属性,但在 update 上应该忽略它。
public class A {
private String strOnCreateAndUpdate; //persist on both create and update
private String strOnCreateOnly; //only persist on create, never on update
//getters & setters
}
在控制器中
@RestController
@RequestMapping(value="/a"
public class ControllerA {
@RequestMapping(method= RequestMethod.POST)
public void create(@Validated @RequestBody A req) {
//create the record
}
@RequestMapping(value="/{id}", method=RequestMethod.PUT)
public void update(@PathVariable Long id, @Validated @RequestBody A req) {
//Update the record by ignoring strOnCreateOnly
}
@RequestMapping(value="/{id}", method=RequestMethod.PATCH)
public void update(@PathVariable Long id, @RequestBody Map<String,Object> reqMap){
//Update the record by ignoring strOnCreateOnly
}
}
我能想到的一种方法(也是一种非常不优雅的方法)是允许解组发生,但在更新方法中,手动将 strOnCreateOnly 设置为其原始值。
但是有没有使用 Spring 4 和 Jackson 的可配置方式(例如,使用注释并忽略属性被解组)?甚至向 API 的调用者发回一个错误,说不允许更新 strOnCreateOnly 也没问题。