Spring Boot - Method Validation

[Last Updated: Jul 1, 2018]

The method validation feature supported by Bean Validation Specification is automatically enabled as long as an implementation (such as hibernate-validator) is on the classpath.

In Spring Boot we even do not have to register MethodValidationPostProcessor or LocalValidatorFactoryBean beans (as compared to core Spring validation setup).




Java Bean

package com.logicbig.example;

import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;

public class User {
  private String name;
  private String email;

Method to validate

package com.logicbig.example;

import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;

public class UserTask {

  public void registerUser(@NotNull @Valid User user) {
      System.out.println("registering user: " + user);

Spring Boot main

public class ExampleMain {

  public static void main(String[] args) {
    ApplicationContext ac =;
      UserTask userTask = ac.getBean(UserTask.class);
      User user = new User();
      try {
      } catch (ConstraintViolationException e) {
          for (ConstraintViolation<?> violation : e.getConstraintViolations()) {
              System.out.println(violation.getPropertyPath() + " " + violation.getMessage());
} must be a well-formed email address must not be empty

Example Project

Dependencies and Technologies Used:

  • Spring Boot 2.0.3.RELEASE
    Corresponding Spring Version 5.0.7.RELEASE
  • spring-boot-starter : Core starter, including auto-configuration support, logging and YAML.
  • hibernate-validator 6.0.10.Final: Hibernate's Bean Validation (JSR-380) reference implementation.
  • JDK 10
  • Maven 3.5.4

Spring Boot - Method Validation Select All Download
  • spring-boot-method-validation
    • src
      • main
        • java
          • com
            • logicbig
              • example
          • resources

    See Also