@NotNull 注释在 Spring 启动应用程序中不起作用

Rah*_*hul 10 java spring spring-mvc spring-boot

下面是我的 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
}
Run Code Online (Sandbox Code Playgroud)

在这里,我试图将 createdDate 字段注释为 @NotNull 但它不起作用。它允许在请求正文中并且在邮递员中执行服务后没有收到任何错误。

我尝试了以下选项,但没有运气。

1)尝试添加maven依赖。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>
Run Code Online (Sandbox Code Playgroud)

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

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

请帮我解决这个问题。

Ani*_* B. 6

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

例如 :

@Controller
public class Controller {

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

        if (bindingResult.hasErrors()) {
            return "some-page";
        }
        return "some-other-page";
    }
}
Run Code Online (Sandbox Code Playgroud)

请参阅此Spring Boot Example On Validating Form Input以供参考。

为什么要使用@Valid注解?

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


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

<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>
Run Code Online (Sandbox Code Playgroud)


bur*_*ete 6

您有一个带有一些请求正文的端点,例如;

@RestController
public class TheController {

    @PostMapping(path = "/doSomething", consumes = "application/json", produces = "application/json")
    public void post(@Valid @RequestBody AbstractDTO request) {
        //code
    }
}
Run Code Online (Sandbox Code Playgroud)

您需要对@Valid请求对象进行注释。只有这样,您才能AbstractDTO/doSomething端点启用验证。

检查这里,进行更深入的细节


小智 5

你有正确的进口吗?
我用import javax.validation.constraints.NotNull;