Generic Top

The early-bird price of the new Learn Spring Security OAuth course packages will increase by $50 on Wednesday:

>> CHECK OUT THE COURSE

1. Overview

When it comes to validating user input, Spring Boot provides strong support for this common, yet critical, task out of the box.

Although Spring Boot supports seamless integration with custom validators, the de-facto standard for performing validation is Hibernate Validator, the Bean Validation framework's reference implementation.

In this tutorial, we'll look at how to validate domain objects in Spring Boot.

Further reading:

Custom Validation MessageSource in Spring Boot

Learn how to register a custom MessageSource for validation messages in Spring Boot.

Difference Between @NotNull, @NotEmpty, and @NotBlank Constraints in Bean Validation

Learn the semantics of the @NotNull, @NotEmpty, and @NotBlank bean validation annotations in Java and how they differ.

2. The Maven Dependencies

In this case, we'll learn how to validate domain objects in Spring Boot by building a basic REST controller.

The controller will first take a domain object, then it will validate it with Hibernate Validator, and finally, it will persist it into an in-memory H2 database.

The project's dependencies are fairly standard:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency> 
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency> 
<dependency> 
    <groupId>com.h2database</groupId> 
    <artifactId>h2</artifactId>
    <version>1.4.197</version> 
    <scope>runtime</scope>
</dependency>

As shown above, we included spring-boot-starter-web in our pom.xml file, because we'll need it for creating the REST controller. Additionally, let's make sure to check the latest versions of spring-boot-starter-jpa and the H2 database on Maven Central.

3. A Simple Domain Class

With our project's dependencies already in place, next, we need to define an example JPA entity class, whose role will just be modeling users.

Let's have a look at this class:

@Entity
public class User {
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    
    @NotBlank(message = "Name is mandatory")
    private String name;
    
    @NotBlank(message = "Email is mandatory")
    private String email;
    
    // standard constructors / setters / getters / toString
        
}

The implementation of our User entity class is pretty anemic indeed. But it shows in a nutshell how to use Bean Validation's constraints to constrain the name and email fields.

For simplicity's sake, we constrained the target fields using only the @NotBlank constraint. Also, we specified the error messages with the message attribute.

Therefore, when Spring Boot validates the class instance, the constrained fields must be not null and their trimmed length must be greater than zero.

Additionally, Bean Validation provides many other handy constraints besides @NotBlank. This allows us to apply and combine different validation rules to the constrained classes. For further information, please read the official bean validation docs.

Since we'll use Spring Data JPA for saving users to the in-memory H2 database, we also need to define a simple repository interface for having basic CRUD functionality on User objects:

@Repository
public interface UserRepository extends CrudRepository<User, Long> {}

4. Implementing a REST Controller

Of course, we need to implement a layer that allows us to get the values assigned to our User object's constrained fields.

Therefore, we can validate them and perform a few further tasks, depending on the validation results.

Spring Boot makes all this seemingly-complex process really simple through the implementation of a REST controller.

Let's look at the REST controller implementation:

@RestController
public class UserController {

    @PostMapping("/users")
    ResponseEntity<String> addUser(@Valid @RequestBody User user) {
        // persisting the user
        return ResponseEntity.ok("User is valid");
    }
    
    // standard constructors / other methods
    
}

In a Spring REST context, the implementation of the addUser() method is fairly standard.

Of course, the most relevant part is the use of the @Valid annotation.

When Spring Boot finds an argument annotated with @Valid, it automatically bootstraps the default JSR 380 implementation — Hibernate Validator — and validates the argument.

When the target argument fails to pass the validation, Spring Boot throws a MethodArgumentNotValidException exception.

5. The @ExceptionHandler Annotation

While it's really handy to have Spring Boot validating automatically the User object passed on to the addUser() method, the missing facet of this process though is how we process the validation results.

The @ExceptionHandler annotation allows us to handle specified types of exceptions through one single method.

Therefore, we can use it for processing the validation errors:

@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
public Map<String, String> handleValidationExceptions(
  MethodArgumentNotValidException ex) {
    Map<String, String> errors = new HashMap<>();
    ex.getBindingResult().getAllErrors().forEach((error) -> {
        String fieldName = ((FieldError) error).getField();
        String errorMessage = error.getDefaultMessage();
        errors.put(fieldName, errorMessage);
    });
    return errors;
}

We specified the MethodArgumentNotValidException exception as the exception to be handled. In consequence, Spring Boot will call this method when the specified User object is invalid.

The method stores the name and post-validation error message of each invalid field in a Map. Next, it sends the Map back to the client as a JSON representation for further processing.

Simply put, the REST controller allows us to easily process requests to different endpoints, validate User objects, and send the responses in JSON format.

The design is flexible enough to handle controller responses through several web tiers, ranging from template engines such as Thymeleaf, to a full-featured JavaScript framework, such as Angular.

6. Testing the REST Controller

We can easily test the functionality of our REST controller with an integration test.

Let's start mocking/autowiring the UserRepository interface implementation, along with the UserController instance and a MockMvc object :

@RunWith(SpringRunner.class) 
@WebMvcTest
@AutoConfigureMockMvc
public class UserControllerIntegrationTest {

    @MockBean
    private UserRepository userRepository;
    
    @Autowired
    UserController userController;

    @Autowired
    private MockMvc mockMvc;

    //...
    
}

Since we're only testing the web layer, we use the @WebMvcTest annotation. It allows us to easily test requests and responses using the set of static methods implemented by the MockMvcRequestBuilders and MockMvcResultMatchers classes.

Now, let's test the addUser() method, with a valid and an invalid User object passed in the request body:

@Test
public void whenPostRequestToUsersAndValidUser_thenCorrectResponse() throws Exception {
    MediaType textPlainUtf8 = new MediaType(MediaType.TEXT_PLAIN, Charset.forName("UTF-8"));
    String user = "{\"name\": \"bob\", \"email\" : \"[email protected]\"}";
    mockMvc.perform(MockMvcRequestBuilders.post("/users")
      .content(user)
      .contentType(MediaType.APPLICATION_JSON_UTF8))
      .andExpect(MockMvcResultMatchers.status().isOk())
      .andExpect(MockMvcResultMatchers.content()
        .contentType(textPlainUtf8));
}

@Test
public void whenPostRequestToUsersAndInValidUser_thenCorrectResponse() throws Exception {
    String user = "{\"name\": \"\", \"email\" : \"[email protected]\"}";
    mockMvc.perform(MockMvcRequestBuilders.post("/users")
      .content(user)
      .contentType(MediaType.APPLICATION_JSON_UTF8))
      .andExpect(MockMvcResultMatchers.status().isBadRequest())
      .andExpect(MockMvcResultMatchers.jsonPath("$.name", Is.is("Name is mandatory")))
      .andExpect(MockMvcResultMatchers.content()
        .contentType(MediaType.APPLICATION_JSON_UTF8));
    }
}

In addition, we can test the REST controller API using a free API lifecycle testing application, such as Postman or Katalon Studio.

7. Running the Sample Application

Finally, we can run our example project with a standard main() method:

@SpringBootApplication
public class Application {
    
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
    
    @Bean
    public CommandLineRunner run(UserRepository userRepository) throws Exception {
        return (String[] args) -> {
            User user1 = new User("Bob", "[email protected]");
            User user2 = new User("Jenny", "[email protected]");
            userRepository.save(user1);
            userRepository.save(user2);
            userRepository.findAll().forEach(System.out::println);
        };
    }
}

As expected, we should see a couple of User objects printed out in the console.

A POST request to the http://localhost:8080/users endpoint with a valid User object will return the String “User is valid”.

Likewise, a POST request with a User object without name and email values will return the following response:

{
  "name":"Name is mandatory",
  "email":"Email is mandatory"
}

8. Conclusion

In this tutorial, we learned the basics of performing validation in Spring Boot.

As usual, all the examples shown in this tutorial are available over on GitHub.

Generic bottom

The early-bird price of the new Learn Spring Security OAuth course packages will increase by $50 on Wednesday:

>> CHECK OUT THE COURSE
newest oldest most voted
Notify of
Kristóf
Guest
Kristóf

This is a SO dummy validation example. I really miss the real life validation scenarios:
– validating a field depending on another field value
– validating a field depending on another object value
– multilingual validation message support

Loredana Crusoveanu
Editor

Hi Kristof,

Yes, this guide is focused on the mechanism of using bean validation in a Spring Boot app, with a simple validation scenario. We have a few other guides for different validation cases:
Spring MVC Custom Validation
Method Constraints with Bean Validation 2.0
Validating Container Elements with Bean Validation 2.0

Cheers.

Alejandro Gervasio
Guest

Kristóf, I really appreciate the comment, but the negative connotation is unnecessary. In fact, the article does cover a down-to-earth situation (I use this approach on a daily basis). Of course, it’s possible to showcase a few other use cases, like the ones you mention, which Bean Validation supports. But the article is strongly focused on teaching the reader how to perform validation in Spring Boot at a basic level. From that point onward, they can implement more complex validation on a per-use-case need. Cascaded and graph validation are out of the article’s scope. Loredana has provided some useful links… Read more »

Comments are closed on this article!