第一步:定义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());
}