一、引入架包
maven地址 点击即可。
<!-- https://mvnrepository.com/artifact/org.hibernate.validator/hibernate-validator -->
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.16.Final</version>
</dependency>
二、创建validator包
1、创建返回模版,
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; } // 实现通用的通过格式化字符串信息获取错误结果的msg方法 public String getErrMsg(){ return StringUtils.join(errorMsgMap.values().toArray(),","); } }
2、创建检验器实现类
@Component public class ValidatorImpl implements InitializingBean { private Validator validator; // 实现效验方法并返回检验结果 public ValidationResult validate(Object bean){ final ValidationResult result= new ValidationResult(); Set<ConstraintViolation<Object>> constraintViolationSet=validator.validate(bean); if(constraintViolationSet.size()>0){ // 有错误 result.setHasErrors(true); constraintViolationSet.forEach(constraintViolation->{ String errMsg=constraintViolation.getMessage(); String propertyName=constraintViolation.getPropertyPath().toString(); result.getErrorMsgMap().put(propertyName,errMsg); }); } return result; } @Override public void afterPropertiesSet() throws Exception { // 将hibernate validtor通过工厂的初始化方式使其实例化 this.validator= Validation.buildDefaultValidatorFactory().getValidator(); } }
三、在javaBeanVo类上添加注解
public class UserModel { private Integer id; @NotBlank(message = "用户名不能为空") private String name; @NotNull(message = "性别不能不填写") private Byte gender; @NotNull(message = "年龄不能不填写") @Min(value =0,message = "年龄必须大于0") @Max(value = 150,message = "祝你寿比南山,请联系官方人员(年龄以150岁封顶为准)") private Integer age; @NotBlank(message = "手机号码不能为空") private String telphone; private String registerMode; private String thirdPartyId; @NotBlank(message = "密码不能为空") private String encrptPassword; }
四、实践
@Autowired ValidatorImpl validator; //方法内写 ValidationResult result=validator.validate(userModel); if (result.isHasErrors()){ throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR,result.getErrMsg()); }