In this article, we article, we will inspect Spring bean validation support. Spring provides a first class support for bean validation API and it’s well integrated in the Spring framework.
Introduction
JSR-303 bean validation has become the validation standard in the Java world. Bean validation API provides an object level constraint declaration and validation facility for the Java application developer, and a constraint metadata repository and query API. Spring bean validation allows us to use these bean validation constraint directly on the Java beans. There are several benefits of this approach
- No need for separate validation configurations.
- Constraints are straight on the domain models.
In this article, we will see how to use bean validation support in your Spring MVC application. This We can use bean validation support at any level within Spring system to validate data (even on the DAO layer).
1. Maven Dependencies
To use Spring bean validation in our project, we need to add validation-api and JSR-303 implementation in our pom.xml file (e.g. Hibernate Validator). For this article, we are using Spring Boot which can pull these dependencies automatically.
1.1 Web Application
If you are creating a web application using Spring Boot, JSR-303 dependencies are part of the spring-boot-starter-web starter. This is how our pom.xml look like:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
1.2 Standalone Application
For Spring Boot standalone application, add the “spring-boot-starter-validation” stater in your pom.xml
file. This is how our pom.xml looks like:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
1.3 Non Spring Boot
If you are not working on Spring Boot application, we need to add following dependencies in our pom.xml
file:
<dependencies>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>${api-version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate-validator-version}</version>
</dependency>
</dependencies>
1.4 Changes with Spring Boot 2.3
If you are using the latest release of Spring Boot, above configuration may not work for you. With Spring Boot 2.3 release, web module does not depend on the validation starter by default anymore. We need to add spring-boot-starter-validation
explicit to use the validation API. Make sure you add the following entry in your pom.xml
file.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
For more detail read validation Starter no longer included in web starters.
2. Spring Bean Validation
If you are working on a Spring MVC application or a REST API, there are three distinct places where we can validate
- Request body
- Path variables.
- Query parameters.
Spring MVC have built in support for validating incoming data for path and query parameters. Let’s see how to use the bean validation for the request body:
3. Sample Java Bean
Let’s create our Java bean class and add JSR-303 bean validation annotations. We will create a simple customer class with some basic validations.
public class Customer implements Serializable {
@NotEmpty(message = "Name can not be empty")
private String name;
@Email(message = "please provide a valid email id")
private String email;
@NotNull(message = "age can not be empty")
@Min(value = 21,message = "We only allow an adult with age 21+")
private int age;
//Getter and setter
}
We added few simple validation rule for our bean. These are simple enough and I am not explaining these :).
4. Spring Bean Validation in Action
Now we have our domain object defined, let’s look at these different validation options:
4.1 JSR-303 – Validate Request Body
Let’s build a simple Spring MVC controller to validate the request body. We consider that our client send customer details to our controller.It will validate the incoming data before storing this information.
@Controller
public class CustomerController {
@GetMapping("/customer")
public String getCustomer(final Model model) {
model.addAttribute("customer", new Customer());
return "customer";
}
@PostMapping("/customer")
public String createCustomer(@Valid Customer customer, BindingResult bindingResult,Model model){
if(bindingResult.hasErrors()){
return "customer";
}
model.addAttribute("msg", "Customer added");
model.addAttribute("customer", customer);
return "customer";
}
}
There is a few important points in the above code:
@Valid
annotation in the method, will validate the Customer data model.- In case of validation error system will send out an error message to the customer.
- Spring framework will create a
Validator
and this will be available for the data validation
4.2 Bean Validation in Action
Let’s run our application for bean validation in action:
Let’s fill some incorrect information to see our Spring bean validation in action:
As visible in the above screenshot, when we sent invalid data to our controller, bean validation kicks in.
Localizing your error messages are a typical need. Please read Internationalization in Spring Boot to set up localized message for your bean validations.
Summary
In this post, we learned Spring bean validation support. We saw how to configure and use JSR303 bean validation API in your Spring MVC application. Source code for this post is available on the GitHub for download.