下面是我的 DTO 类。
public class AbstractDTO extends BaseDTO {
private Integer createdBy;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = DATE_FORMAT)
@NotNull(message = "createdDate may not be null")
private LocalDateTime createdDate;
private Integer lastModifiedBy;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = DATE_FORMAT)
private LocalDateTime lastModifiedDate;
private Boolean isActive;
// getter & setters
}
在这里,我试图将 createdDate 字段注释为 @NotNull 但它不起作用吗?它允许在请求正文中并且在邮递员中执行服务后不会出现任何错误。
我尝试了以下选项但没有运气。
1) 试图添加 maven 依赖项。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
2) 试图将 DTO 类注释为 @Validated
3) 试图用@NotNull 注释createdDate 字段@Valid 但仍然不走运。
请帮我解决这个问题。
原文由 Rahul 发布,翻译遵循 CC BY-SA 4.0 许可协议
您的 DTO 类是正确的。您必须使用
@Valid
注释。例如 :
请参阅此 Spring Boot Example On Validating Form Input 以供参考。
为什么要使用
@Valid
注释?这允许您验证应用于类的数据成员的约束集。
但是,如果您的项目中有基于 XML 的配置,则必须在下面给出的 applicationContext.xml 中添加它。 (来源: 这里)