目录

一、背景

二、hibernate-validator

1.maven

2.校验工具类

3.自定义校验注解

4.校验实体类

5.main函数测试

三、测试结果


一、背景

在某些项目场景中,需要使用代码校验实体类的参数值是否符合需求,并且返回值是动态的情况下,此时需要校验工具类来实现此功能。

二、hibernate-validator

1.maven

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>6.0.16.Final</version>
        </dependency>

2.校验工具类

package com.asyf.demo.other_api.hibernatevalidator;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.groups.Default;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @Description 实体校验工具类
 */
@Slf4j
public class ValidateUtil {

    /**
     * 验证器
     */
    private static Validator validator;

    static {
//        validator = Validation.buildDefaultValidatorFactory().getValidator();
        ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class)
                .configure()
                // 快速失败模式
                .failFast(false)
                .buildValidatorFactory();
        validator = validatorFactory.getValidator();
    }


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

    /**
     * 校验指定实体的指定属性是否存在异常
     *
     * @param obj
     * @param propertyName
     * @param <T>
     * @return
     */
    public static <T> ValidationResult validateProperty(T obj, String propertyName) {
        Set<ConstraintViolation<T>> validateSet = validator.validateProperty(obj, propertyName, Default.class);
        return buildValidationResult(validateSet);
    }

    /**
     * 将异常结果封装返回
     *
     * @param validateSet
     * @param <T>
     * @return
     */
    private static <T> ValidationResult buildValidationResult(Set<ConstraintViolation<T>> validateSet) {
        ValidationResult validationResult = new ValidationResult();
        if (!validateSet.isEmpty()) {
            validationResult.setHasErrors(true);
            Map<String, String> errorMsgMap = new HashMap<>();
            for (ConstraintViolation<T> constraintViolation : validateSet) {
                errorMsgMap.put(constraintViolation.getPropertyPath().toString(), constraintViolation.getMessage());
            }
            validationResult.setErrorMsg(errorMsgMap);
        }
        return validationResult;
    }

    public static void main(String[] args) {
        User user = new User();
        ValidationResult validationResult = ValidateUtil.validateEntity(user);
        log.info(JSONUtil.toJsonStr(validationResult));
        //og.info(validationResult.getMessage());
    }

}
package com.asyf.demo.other_api.hibernatevalidator;

import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.text.MessageFormat;
import java.util.Map;

@Data
public class ValidationResult {
    /**
     * 是否有异常
     */
    private boolean hasErrors;

    /**
     * 异常消息记录
     */
    private Map<String, String> errorMsg;

    /**
     * 获取异常消息组装
     *
     * @return
     */
    public String getMessage() {
        if (errorMsg == null || errorMsg.isEmpty()) {
            return StringUtils.EMPTY;
        }
        StringBuilder message = new StringBuilder();
        errorMsg.forEach((key, value) -> {
            message.append(MessageFormat.format("{0}:{1} \r\n", key, value));
        });
        return message.toString();
    }

}

3.自定义校验注解

package com.asyf.demo.other_api.hibernatevalidator;

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = MyConstraintValidator.class)
public @interface MyValidatorAnnotation {

    String message() default "性别有误";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    String type() default "abc";

}
package com.asyf.demo.other_api.hibernatevalidator;

import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

@Slf4j
public class MyConstraintValidator implements ConstraintValidator<MyValidatorAnnotation, String> {

    private MyValidatorAnnotation annotation;

    public MyConstraintValidator() {
        //每添加一次注解会实例化一个对象
        //log.info("构造函数");
    }

    @Override
    public void initialize(MyValidatorAnnotation annotation) {
        //log.info("初始化");
        this.annotation = annotation;
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        log.info("校验 type:{}", annotation.type());
        //禁用默认的message的值
        context.disableDefaultConstraintViolation();
        //重新添加错误提示语句
        context.buildConstraintViolationWithTemplate("重新添加错误提示语句").addConstraintViolation();
        //返回校验结果
        return "正确的值".equals(value);
    }

}

4.校验实体类

package com.asyf.demo.other_api.hibernatevalidator;

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;

import javax.validation.constraints.NotNull;

@Data
public class User {

    //    @NotBlank
    @MyValidatorAnnotation(type = "1", message = "name错误")
    private String name;

    @NotNull
    @JsonIgnore
    private Integer age;

    @MyValidatorAnnotation(type = "2", message = "email错误")
    private String email;

}

5.main函数测试

public static void main(String[] args) {
        User user = new User();
        ValidationResult validationResult = ValidateUtil.validateEntity(user);
        log.info(JSONUtil.toJsonStr(validationResult));
        //og.info(validationResult.getMessage());
    }
三、测试结果
 INFO [main] - 校验 type:2
 INFO [main] - 校验 type:1
 INFO [main] - {"hasErrors":true,"errorMsg":{"name":"重新添加错误提示语句","email":"重新添加错误提示语句","age":"不能为null"}}