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);
}
}
}
OutputNumber (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);
}
}
}
OutputNumber (class java.lang.Integer) cannot be negative. Found: -1
Example ProjectDependencies and Technologies Used: - spring-context 6.1.2 (Spring Context)
Version Compatibility: 6.1.0 - 6.1.2 Version compatibilities of spring-context with this example: Versions in green have been tested.
- JDK 17
- Maven 3.8.1
|