Spring 手动开启注解验证

Spring 手动开启注解验证

验证工具类

package com.xjrsoft.common.utils;

import cn.hutool.core.util.StrUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 手动开启注解验证
 *
 * @author wanglin
 * @version 1.0
 * @date 2022-06-28 周二
 */
public class ValidateUtil {

    /**
     * 验证器
     */
    private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();


    public static <T> List<String> validateEntity(T obj) {
        //解析校验结果
        Set<ConstraintViolation<T>> validateSet = validator.validate(obj, Default.class);
        return buildValidationResult(validateSet, null);
    }

    public static <T> void validateEntityParams(T obj) {
        //解析校验结果
        Set<ConstraintViolation<T>> validateSet = validator.validate(obj, Default.class);
        buildValidationResult(validateSet);
    }

    /**
     * 校验实体,返回实体所有属性的校验结果
     *
     * @param obj
     * @param 
     * @return
     */
    public static <T> List<String> validateEntity(T obj, int lineNo) {
        //解析校验结果
        Set<ConstraintViolation<T>> validateSet = validator.validate(obj, Default.class);
        return buildValidationResult(validateSet, lineNo);
    }


    /**
     * 将异常结果封装返回
     *
     * @param validateSet
     * @param 
     * @return
     */
    private static <T> List<String> buildValidationResult(Set<ConstraintViolation<T>> validateSet, Integer lineNo) {
        List<String> errorList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(validateSet)) {
            for (ConstraintViolation<T> constraintViolation : validateSet) {
                if (lineNo != null) {
                    errorList.add(StrUtil.format("第{}行:{}", lineNo, constraintViolation.getMessage()));
                } else {
                    errorList.add(constraintViolation.getMessage());
                }

            }
        }
        return errorList;
    }

    /**
     * 实体参数验证,若有错误信息则直接抛出
     *
     * @param validateSet
     * @param 
     * @return
     */
    private static <T> void buildValidationResult(Set<ConstraintViolation<T>> validateSet) {
        if (CollectionUtils.isNotEmpty(validateSet)) {
            for (ConstraintViolation<T> constraintViolation : validateSet) {
                Assert.isTrue(StringUtils.isEmpty(constraintViolation.getMessage()), constraintViolation.getMessage());
            }
        }
    }
}

关注林哥,持续更新哦!!!★,°:.☆( ̄▽ ̄)/$:.°★ 。

你可能感兴趣的:(Java,工具类笔记,Spring笔记,spring,boot,java,spring)