问题背景
hibernate-validator 一般通过在对象或者类上加注解的方式对Controller中的方法参数进行校验,
现需要在其他地方也可对主动对对象中的参数进行校验
代码
import lombok.experimental.UtilityClass;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.constraints.NotNull;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
* hibernate-validator 主动调用进行参数校验
*
* @author lyn
* @date 2023/4/7 13:09
*/
@UtilityClass
public class ManualValidUtil {
private static final Validator VALIDATOR = Validation.buildDefaultValidatorFactory().getValidator();
public static <T> void validObj(@NotNull T obj) {
Set<ConstraintViolation<T>> violations = VALIDATOR.validate(obj);
if (!violations.isEmpty()) {
// 处理校验失败的情况
throw new IllegalArgumentException("参数异常: " + violations.stream().map(ConstraintViolation::getMessage).collect(Collectors.joining(",")));
}
}
public static <T> void validList(@NotNull List<T> list) {
validate(list);
}
public static <T> void validSet(@NotNull Set<T> set) {
validate(set);
}
private static <T> void validate(Collection<T> collection) {
Set<ConstraintViolation<T>> violations = new HashSet<>();
for (T obj : collection) {
violations.addAll(VALIDATOR.validate(obj));
}
if (!violations.isEmpty()) {
// 处理校验失败的情况
throw new IllegalArgumentException("参数异常: " + violations.stream().map(ConstraintViolation::getMessage).collect(Collectors.joining(",")));
}
}
}
标签:hibernate,java,校验,validator,static,import,violations,validate
From: https://www.cnblogs.com/lyn8100/p/17297477.html