SpringBoot 通用Validator

第一步,pom.xml引入hibernate-validator

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

第二步,编写验证结果Bean,存放“验证是否有错误和错误信息”

import org.apache.commons.lang3.StringUtils;
import java.util.HashMap;
import java.util.Map;

public class ValidationResult {

    // 校验结果是否有错
    private boolean hasErrors = false;

    // 存放错误信息的Map
    private Map<String, String> errorMsgMap = new HashMap<>();

    public boolean isHasErrors() {
        return hasErrors;
    }

    public void setHasErrors(boolean hasErrors) {
        this.hasErrors = hasErrors;
    }

    public Map<String, String> getErrorMsgMap() {
        return errorMsgMap;
    }

    public void setErrorMsgMap(Map<String, String> errorMsgMap) {
        this.errorMsgMap = errorMsgMap;
    }

    // 将所有的错误信息拼接成一个字符串
    public String getErrorMsg(){
        return StringUtils.join(errorMsgMap.values().toArray(), ",");
    }
}

第三步,

import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;


/**
 * InitializingBean接口为bean提供了初始化方法的方式,它只包括afterPropertiesSet方法,凡是继承该接口的类,在初始化bean的时候都会执行该方法。
 * Spring初始化完成后,会回调ValidatorImpl的afterPropertiesSet()方法
 */
@Component
public class ValidatorImpl implements InitializingBean {
   
    // 注意需要引用: javax.validation.Validator
    private Validator validator;  

    // 实现校验方法并返回校验结果
    public ValidationResult validate(Object bean){
        ValidationResult validationResult = new ValidationResult();
        Set<ConstraintViolation<Object>> constraintViolationSet = validator.validate(bean);
        if(constraintViolationSet.size() > 0){
            // 大于0 表示有错误
            validationResult.setHasErrors(true);
            for (ConstraintViolation<Object> constraintViolation : constraintViolationSet) {
                String errorMsg = constraintViolation.getMessage();
                String propertyName = constraintViolation.getPropertyPath().toString();
                validationResult.getErrorMsgMap().put(propertyName, errorMsg);
            }
        }
        return validationResult;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        // 将hibernate validator通过工厂的初始化方式使其实例化
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }
}

第四步,在Model中定义限制条件,并在业务逻辑中使用验证

public class UserModel {

    private Integer id;

    @NotBlank(message = "name不能为空")
    private String name;

    @NotNull(message = "性别不能为空")
    private Byte gender;

    @NotNull(message = "年龄不能为空")
    @Min(value = 0, message = "年龄必须小于0")
    @Max(value = 150, message = "年龄不能大于150")
    private Integer age;

    @NotNull(message = "手机号码不能为空")
    @Size(min = 11, max = 11, message = "手机号码必须为11位")
    private String telphone;

    @NotNull(message = "注册方式不能为空")
    private String registerMode;
    private String thirdPartyId;

    @NotNull(message = "密码不能为空")
    private String encrptPassword;
}

======================================================
ValidationResult validationResult = validator.validate(userModel);
if(validationResult.isHasErrors()){
    throw new BusinessException(EnumBusinessError.PARAMETER_VALIDATION_ERROR, validationResult.getErrorMsg());
}
posted @ 2019-02-19 21:46  Vincen_shen  阅读(657)  评论(0编辑  收藏  举报