Close

Spring - Validator Factory Methods Examples

[Last Updated: Dec 22, 2023]

Spring core 6.1 introduce three new methods in Validator interface

A method to validate objects individually:

default Errors validateObject(Object target)

Two factory methods to create validators

static <T> Validator forInstanceOf(Class<T> targetClass,  BiConsumer<T,Errors> delegate)
static <T> Validator forType(Class<T> targetClass, BiConsumer<T,Errors> delegate)

Let's see example of these new methods

Examples

Using Validator#forInstanceOf

package com.logicbig.example;

import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import java.math.BigDecimal;

public class ValidatorForInstanceOfExample {

  public static void main(String[] args) {
      Validator validator = Validator.forInstanceOf(Number.class, (number, errors) -> {
          if (number.doubleValue() < 0) {
              errors.reject("number.negative", String.format("Number (%s) cannot be negative. Found: %s",
                      number.getClass(), number));
          }
      });

      if (validator.supports(Integer.class)) {
          Errors errors = validator.validateObject(Integer.valueOf(-1));
          errors.getAllErrors().stream()
                  .map(DefaultMessageSourceResolvable::getDefaultMessage)
                  .forEach(System.out::println);
      }
      if (validator.supports(BigDecimal.class)) {
          Errors errors = validator.validateObject(BigDecimal.valueOf(-10));
          errors.getAllErrors().stream()
                  .map(DefaultMessageSourceResolvable::getDefaultMessage)
                  .forEach(System.out::println);
      }
  }
}

Output

Number (class java.lang.Integer) cannot be negative. Found: -1
Number (class java.math.BigDecimal) cannot be negative. Found: -10

Using Validator#forType

package com.logicbig.example;

import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import java.math.BigDecimal;

public class ValidatorForTypeExample {

  public static void main(String[] args) {
      Validator validator = Validator.forType(Integer.class, (number, errors) -> {
          if (number.doubleValue() < 0) {
              errors.reject("number.negative", String.format("Number (%s) cannot be negative. Found: %s",
                      number.getClass(), number));
          }
      });

      if (validator.supports(Integer.class)) {
          Errors errors = validator.validateObject(Integer.valueOf(-1));
          errors.getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).forEach(System.out::println);
      }
      if (validator.supports(BigDecimal.class)) {
          Errors errors = validator.validateObject(BigDecimal.valueOf(-10));
          errors.getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).forEach(System.out::println);
      }
  }
}

Output

Number (class java.lang.Integer) cannot be negative. Found: -1

Example Project

Dependencies and Technologies Used:

  • spring-context 6.1.2 (Spring Context)
     Version Compatibility: 6.1.0 - 6.1.2Version List
    ×

    Version compatibilities of spring-context with this example:

    • 6.1.0
    • 6.1.1
    • 6.1.2

    Versions in green have been tested.

  • JDK 17
  • Maven 3.8.1

Validator#forInstanceOf() and Validator#forType() examples Select All Download
  • spring-validator-factory-methods
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • ValidatorForInstanceOfExample.java

    See Also