@NotNull 注释在 Spring 启动应用程序中不起作用 [英] @NotNull annotation is not working in Spring boot application

查看:22
本文介绍了@NotNull 注释在 Spring 启动应用程序中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的 DTO 课程.

Below is my DTO class.

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 但它不起作用.它在请求正文中允许并且在邮递员中执行服务后没有出现任何错误.

Here I am trying to annotate createdDate field as @NotNull but is it not working. It is allowing in request body and after executing the service in postman not getting any error.

我尝试了以下选项,但没有成功.

I have tried below options but no luck.

1) 尝试添加 maven 依赖项.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

2) 尝试将 DTO 类注释为 @Validated

3) 尝试使用 @NotNull 注释 createdDate 字段 @Valid 但仍然没有运气.

请帮我解决这个问题.

推荐答案

您的 DTO 类是正确的.您必须使用 @Valid 注释.

Your DTO class is correct. You have to use @Valid annotation.

例如:

@Controller
public class Controller {

    @PostMapping("/")
    public String checkPersonInfo(@Valid AbstractDTO abstractDTO, BindingResult bindingResult) {

        if (bindingResult.hasErrors()) {
            return "some-page";
        }
        return "some-other-page";
    }
}

参考此Spring Boot 验证表单输入示例 供参考.

Refer to this Spring Boot Example On Validating Form Input for reference.

为什么要使用@Valid注解?

这允许您验证应用于类数据成员的约束集.

但是,如果您的项目中有基于 XML 的配置,那么您必须在下面给出的 applicationContext.xml 中添加以下内容.(来源:此处)

However, if you have XML based configuration in your project, then you have to add this below in the applicationContext.xml given below. (Source : here)

<bean
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="webBindingInitializer">
        <bean
            class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
            <property name="validator" ref="validator" />
        </bean>
    </property>
</bean> 

    <bean id="validator"
        class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
    </bean>

这篇关于@NotNull 注释在 Spring 启动应用程序中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆