在Spring中,我可以将@RequestBody中的单个字段设为可选吗?

pow*_*eed 7 java spring spring-boot

我有这样的路线:

@PostMapping("/")
public void sendNotification(@RequestBody PostBody postBody){...}
Run Code Online (Sandbox Code Playgroud)

类中的字段PostBody是:

public class PostBody {
    private String type;
    private String payload;
    private String recipients;
    private String callerId;
Run Code Online (Sandbox Code Playgroud)

我想知道,我可以将这些字段中的一个或多个字段设置为可选,但不是全部吗?

我想如果我使用(require = false),所有字段都是可选的,对吗?

那么有办法这样做吗?

谢谢!

Jor*_*orn 9

您可以为此使用标准验证注释。@NotNull只需用或注释必填字段@NotEmpty,然后添加@Valid到您的请求正文参数中:

@PostMapping("/")
public void sendNotification(@Valid @RequestBody PostBody postBody){...}

public class PostBody {
    @NotEmpty private String type; // String must be non-null and contain at least one character
    @NotNull private String payload; // fails on null but not on ""
    private String recipients; // allows null or "" or any value
    private String callerId;
}
Run Code Online (Sandbox Code Playgroud)

  • @powerseed 它是“spring-boot-starter-validation” (2认同)