hibernate-validator 主动调用进行参数校验

说明

除了在 Controller 方法参数上使用注解进行校验外,还可以手动创建 Validator 对象并调用其 validate() 方法对对象中的参数进行校验

代码

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(",")));
        }
    }
}

实体类

@Data
public class TestObj {
    @NotNull
    private String name;
    @NotBlank
    @Size(min = 6, max = 20)
    private String password;
}
posted @ 2023-04-07 21:47  进击的小蔡鸟  阅读(147)  评论(0编辑  收藏  举报