1. 程式人生 > >SpringBoot 定義通過字段驗證

SpringBoot 定義通過字段驗證

ash prop ger 實例 after override ide 字符 map()

第一步:定義ValidationResult類

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;
    }

    // 實現通用的 通過格式化字符串信息獲取 所有錯誤結果的Message方法
    public String getErrorMsg(){
        return StringUtils.join(errorMsgMap.values().toArray(), ",");
    }
}

第二步:定義ValidatorImpl實現類

/**
 * InitializingBean接口為bean提供了初始化方法的方式,它只包括afterPropertiesSet方法,凡是繼承該接口的類,在初始化bean的時候都會執行該方法。
 * Spring初始化完成後,會回調ValidatorImpl的afterPropertiesSet()方法
 */
@Component
public class ValidatorImpl implements InitializingBean {

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

第三步,在業務邏輯中調用

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;
    @Autowired
    private ValidatorImpl validator;

    @Transactional
    public void register(UserModel userModel) throws BusinessException {
        if(userModel == null){
            throw new BusinessException(EnumBusinessError.PARAMETER_VALIDATION_ERROR);
        }
        // 
        ValidationResult validationResult = validator.validate(userModel);
        if(validationResult.isHasErrors()){
            throw new BusinessException(EnumBusinessError.PARAMETER_VALIDATION_ERROR, validationResult.getErrorMsg());
        }

SpringBoot 定義通過字段驗證