Close

Spring Boot - Method Validation

[Updated: Jul 1, 2018, Created: 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).

Example

pom.xml

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
   <groupId>org.hibernate.validator</groupId>
   <artifactId>hibernate-validator</artifactId>
</dependency>

Java Bean

package com.logicbig.example;

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

public class User {
  @NotEmpty
  private String name;
  @Email
  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;

@Component
@Validated
public class UserTask {

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

Spring Boot main

@SpringBootApplication
public class ExampleMain {

  public static void main(String[] args) {
    ApplicationContext ac =  SpringApplication.run(ExampleMain.class);
      UserTask userTask = ac.getBean(UserTask.class);
      User user = new User();
      user.setEmail("tony-example.com");
      try {
          userTask.registerUser(user);
      } catch (ConstraintViolationException e) {
          for (ConstraintViolation<?> violation : e.getConstraintViolations()) {
              System.out.println(violation.getPropertyPath() + " " + violation.getMessage());
          }
      }
  }
}
registerUser.user.email must be a well-formed email address
registerUser.user.name 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