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

标签 java spring spring-boot

我有一条路线,如:

@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/

相关文章:

java - corrupted double-linked list error 第一次运行程序时,后续运行正常

java - java导入本地库错误

java - LibGdx 项目设置 - 生成的项目存在 gradle 错误

java - 在 Spring Boot 应用程序中未针对 hibernate 和 spring 过滤 Log4j2 日志级别

spring-boot - 当连接被 RabbitMQ 阻塞时,Spring amqp 不会引发超时异常

java - LibGDX 使视口(viewport)大于屏幕

spring - 创建类路径资源中定义的名称为 'entityManagerFactory' 的 bean 时出错

java - 我想用 Thymeleaf 缩写字符串

spring - mvn clean install 会导致 Surefire 错误

java - 通过前缀获取 application.properties 的子集