Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

How to add spring boot validator in spring boot?


Asked by Roger Fitzgerald on Dec 12, 2021 Spring



Spring boot by default add hibernate validator’s dependency and configure it on the classpath. Therefore, we don’t have to write any code to add hibernate validator into our project. So, Let’s change the above User class and add a constraint called @NotEmpty.
One may also ask,
To customize the validation, we will use Hibernate Validator, which is one of the implementations of the bean validation api. We get Hibernate Validator for free when we use Spring Boot Starter Web. So, we can get started with implementing the validations. Before we add validations, we need to add a dependency.
Just so, The validation class implements the ConstraintValidator interface, and must also implement the isValid method; it's in this method that we defined our validation rules. Naturally, we're going with a simple validation rule here in order to show how the validator works.
Consequently,
Enable validation on Spring Rest Controller by adding @Valid annotation in addition to @RequestBody. 4. To customize response validation we need to extend ResponseEntityExceptionHandler class and override handleMethodArgumentNotValid (MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) method.
In fact,
To activate Spring MVC, you would normally add @EnableWebMvc to the Application class. But Spring Boot’s @SpringBootApplication already adds this annotation when it detects spring-webmvc on your classpath.