Close

Spring Annotation Based Validation

[Last Updated: Jan 21, 2022]

In this tutorial we will see how to perform JSR 349/303 annotation based validation in a Spring application.

Please check out our Java EE Bean Validation tutorials if not already familiar with it.

The Spring specific class LocalValidatorFactoryBean implements javax.validation.Validator, javax.validation.ValidatorFactory and org.springframework.validation.Validator interfaces.
This class wraps standard JSR 349/303 bean validation bootstrapping process and also wraps the access around org.springframework.validation.Validator.
LocalValidatorFactoryBean allows as to inject javax.validation.Validator .
We can also inject org.springframework.validation.Validator instead of javax.validation.Validator and then in that case we will be using Spring validation API to perform validation.

Example

A bean using validation annotations

package com.logicbig.example;

import javax.validation.constraints.DecimalMin;
import javax.validation.constraints.Future;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.Date;

public class Order {
  @NotNull(message = "{date.empty}")
  @Future(message = "{date.future}")
  private Date date;

  @NotNull(message = "{price.empty}")
  @DecimalMin(value = "0", inclusive = false, message = "{price.invalid}")
  private BigDecimal price;
    .............
}

Spring configuration

package com.logicbig.example;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import javax.validation.Validator;

@Configuration
public class Config {

  @Bean
  public ClientBean clientBean() {
      return new ClientBean();
  }

  @Bean
  public Validator validatorFactory() {
      return new LocalValidatorFactoryBean();
  }
}

Performing Validation

package com.logicbig.example;

import org.springframework.beans.factory.annotation.Autowired;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.Locale;
import java.util.Set;

public class ClientBean {
  @Autowired
  Validator validator;

  public void processOrder(Order order) {
      if (validateOrder(order)) {
          System.out.println("processing " + order);
      }
  }

  private boolean validateOrder(Order order) {
      Locale.setDefault(Locale.US);
      Set<ConstraintViolation<Order>> c = validator.validate(order);
      if (c.size() > 0) {
          System.err.println("Order validation errors:");
          c.stream().map(v -> v.getMessage()).forEach(System.err::println);
          return false;
      }
      return true;
  }
}

Main class

package com.logicbig.example;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import java.util.Calendar;

public class ValidationJSR349Example {

  public static void main(String[] args) {
      AnnotationConfigApplicationContext context =
              new AnnotationConfigApplicationContext(Config.class);

      Order order = new Order();
      //order.setPrice(BigDecimal.TEN);
      Calendar calendar = Calendar.getInstance();
      calendar.clear();
      calendar.set(2021,1,1, 0,0,0);
      order.setDate(calendar.getTime());

      ClientBean bean = context.getBean(ClientBean.class);
      bean.processOrder(order);
  }
}

Output

Order validation errors:
{date.future}
{price.empty}

Example Project

Dependencies and Technologies Used:

  • spring-context 4.3.3.RELEASE (Spring Context)
  • hibernate-validator 5.2.4.Final (Hibernate's Bean Validation (JSR-303) reference implementation)
  • javax.el-api 2.2.4 (Expression Language API 2.2)
  • javax.el 2.2.4 (Expression Language 2.2 Implementation)
  • JDK 1.8
  • Maven 3.8.1

Spring - Annotation based validations Select All Download
  • spring-annotation-based-validations
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • Order.java

    See Also