我有一条路线,如:
@PostMapping("/")
public void sendNotification(@RequestBody PostBody postBody){...}
以及 PostBody
中的字段类是:public class PostBody {
private String type;
private String payload;
private String recipients;
private String callerId;
我想知道,我可以将这些字段中的一个或多个设为可选,但不是全部可选吗?我想如果我使用
(require = false)
,所有字段都是可选的,对吗?那么有没有办法做到这一点?
谢谢!
最佳答案
您可以为此使用标准验证注释。只需用 @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;
}
关于java - 在 Spring 中,我可以将 @RequestBody 中的单个字段设为可选吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62922771/