Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@NotNull annotation is not working in Spring boot application

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
}

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) Tried to add maven dependency.

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

2) Tried to annotate DTO class as @Validated

3) Tried to annotate createdDate field @Valid with @NotNull but still not luck.

Please help me out with this issue.

like image 884
Rahul Avatar asked Oct 01 '19 10:10

Rahul


People also ask

What is @NotNull in Spring boot?

@NotNull: a constrained CharSequence, Collection, Map, or Array is valid as long as it's not null, but it can be empty. @NotEmpty: a constrained CharSequence, Collection, Map, or Array is valid as long as it's not null, and its size/length is greater than zero.

What is @NotNull annotation in Java?

@NotNull The @NotNull annotation is, actually, an explicit contract declaring that: A method should not return null. Variables (fields, local variables, and parameters) cannot hold a null value.

What is the difference between @NotNull and @NotBlank?

@NotNull : The CharSequence, Collection, Map or Array object is not null, but can be empty. @NotEmpty : The CharSequence, Collection, Map or Array object is not null and size > 0. @NotBlank : The string is not null and the trimmed length is greater than zero.

What exception does @NotNull throw?

Hi, when using the @NotNull annotation, IntelliJ will generate bytecode to throw an IllegalArgumentException when a null is passed/returned.


2 Answers

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

For example :

@Controller
public class Controller {

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

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

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

Why to use @Valid annotation ?

This allows you to validate the set of constraints applied on the data members of a class.


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>
like image 149
Anish B. Avatar answered Sep 20 '22 17:09

Anish B.


You have an endpoint with some request body like;

@RestController
public class TheController {

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

You need to have @Valid annotation for the request object. Only with this you'd have validation enabled for AbstractDTO for /doSomething endpoint.

Check here, for more in depth details

like image 35
buræquete Avatar answered Sep 18 '22 17:09

buræquete