1

使用 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 也没问题。

4

1 回答 1

0

我认为您可以使用@JsonView它。

杰克逊文档链接

而您创建一个View将表示操作类型的类:(更新、创建、全部)。像这样的东西

// View definitions:
class Views {
    static class Common { }
    static class Update extends Common { }
    static class Create extends Common { }
}   

像这样将它应用到你的班级

public class A {
    @JsonView(View.Common.class)
    private String strOnCreateAndUpdate; //persist on both create and update

    @JsonView(View.Create.class)
    private String strOnCreateOnly; //only persist on create, never on update
    //getters & setters
} 

在您的 create 方法上,将类与Create视图编组。然后在更新方法上,只需使用CommonUpdate视图。

于 2014-07-26T04:54:41.300 回答