Search code examples
springspring-annotationsnotnull

@NotNull annotation is not working in spring boot


I am new to Spring Boot and I have this problem.

enter image description here

and I still get 200 OK even though I don't provide "data"

enter image description here

Why do you think this is happening?

Any Help is appreciated.

Best


Solution

  • You should use @RequestParam as opposed to @PathParams in this case. But validation can also be applied to @PathParam

    @GetMapping(path = "extra")
    public String doExtraThing(@RequestParam("data") String data) {
        return "Data is: " + data;
    }
    

    Using @NotNull

    If you hit this api directly from browser

    http://localhost:8080/demo/extra
    

    You should get something in the console, because your default request parameter is mandatory.

    2021-03-06 08:55:20.872  WARN 2936 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'data' is not present]
    

    To make it optional use

    @RequestParam(value = "data", required = false) String data
    

    Now when you try to hit http://localhost:8080/demo/extra?data=, you should get

    Data is:
    

    Now, when you make it required = false and add @NotNull annotation from javax.validation.constraints package and hit the api again you should get 503 internal server error.

    javax.validation.ConstraintViolationException: doExtraThing.data: must not be null
    

    Using @NotBlank:

    You can achieve the same behavior using @NotBlank from javax.validation.constraints

    @NotNull Validate that the object is not null.

    @NotBlank check for character sequence's (e.g. string) trimmed length is not empty.

    You would use @NotBlank on strings more here