标签:build object nes art uil model map 格式 ram
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>
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(),","); } }
@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(); } }
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()); }
标签:build object nes art uil model map 格式 ram
原文地址:https://www.cnblogs.com/codeByWei/p/10993900.html