Spring 引导:如何在 POST 请求中将字段设置为必填字段,而在 PUT 请求中它应该是可选的

Spring Boot: How to make a field as mandatory in POST request while in PUT request it should be optional

我正在使用实体 class。 考虑字段 "Name" 在请求正文中对于 POST 请求和更新是强制性的,即在 PUT 请求中 "Name" 字段应该是可选的。我们不需要再次传递 "Name" 字段,这是没有必要的。所以我想在 POST 请求正文中使 "Name" 属性成为必需属性,在 PUT 请求正文中成为可选属性。

您可以在 JSR303 注释中使用组参数。

@NotEmpty 注释在通过 "Existing" 接口访问时应用:

public class Greeting {

  private final long id;
  @NotEmpty(groups = Existing.class)
  private final String content;

  public Greeting(long id, String content) {
      this.id = id;
      this.content = content;
  }

  public long getId() {
      return id;
  }

  public String getContent() {
      return content;
  }

  public interface Existing {
  }
}

注意 @Validated(Existing.class) PutMapping 上的注释

@PostMapping("/greeting")
public Greeting newGreeting( @RequestBody Greeting gobj) {
    return new Greeting(counter.incrementAndGet(),
            String.format(template, gobj.getContent()));
}

@PutMapping("/greeting")
public Greeting updateGreeting(@Validated(Existing.class) @RequestBody Greeting gobj) {
    return new Greeting(gobj.getId(),
            String.format(template, gobj.getContent()));
}

对于上面的例子 Json body {"id": 1} 将适用于 POST 但对于 PUT 你会得到 HTTP 400 告诉你 "content parameter must not be empty"。 {"id": 1, "content":"World"} 两种方法都将被接受。