1.引入依赖
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.15.Final</version>
</dependency>
2.Hibernate Validator常用注解
注解 释义
@Null 必须为null
@NotNull 不能为null
@AssertTrue 必须为true
@AssertFalse 必须为false
@Min 必须为数字,其值大于或等于指定的最小值
@Max 必须为数字,其值小于或等于指定的最大值
@DecimalMin 必须为数字,其值大于或等于指定的最小值
@DecimalMax 必须为数字,其值小于或等于指定的最大值
@Size 集合的长度
@Digits 必须为数字,其值必须再可接受的范围内
@Past 必须是过去的日期
@Future 必须是将来的日期
@Pattern 必须符合正则表达式
@Email 必须是邮箱格式
@Length 长度范围
@NotEmpty 不能为null,长度大于0
@Range 元素的大小范围
@NotBlank 不能为null,字符串长度大于0(限字符串)
3.自定义注解
(1).新建注解类
@Target({ ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = BusinessTypeContrainValidator.class)
public @interface BusinessType {
//注解赋值需要的
String[] value() default { };
//错误信息
String message() default "业务类型有误";
//分组去校验
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
(2).新建注解的逻辑处理类
/**
* @author JK
* @title: BusinessTypeContrainValidator
* @description: 业务类型的校验注解类
* @date 2019/7/1613:40
*/
public class BusinessTypeContrainValidator implements ConstraintValidator<BusinessType,String> {
@Override
public void initialize(BusinessType constraintAnnotation) {
String[] value = constraintAnnotation.value();
for (String s : value) {
System.out.println(s+" ");
}
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
//逻辑处理类,若返回是false,那么提示上面的message
return value!=null && (BusinessTypeEnums.isInclude(value));
}
}
(3).测试
public String checkValidator(BindingResult result) {
StringBuilder stringBuilder = new StringBuilder();
if (result.hasErrors()){
for (ObjectError error : result.getAllErrors()) {
stringBuilder.append(error.getDefaultMessage()).append(";");
}
}
if (StringUtils.isNotBlank(stringBuilder)){
ApiResponse apiResponse = new ApiResponse(ResponseCodeEnums.param_error);
apiResponse.setData("\""+stringBuilder.toString()+"\"");
return apiResponse.toString();
}
return "";
}
34.自定义方法类注解
image.png这里不进行讲解,只是进行代码的保存
@Target({ ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = CheckAssetIdAndCapitalIdConstraintValidator.class)
@Documented //对类进行注解的时候这里一定要加上
public @interface CheckAssetIdAndCapitalId {
String message() default "资金方与资产方未存在协议!";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
String[] fields() default {"assetId","capitalId"};
}
public class CheckAssetIdAndCapitalIdConstraintValidator implements ConstraintValidator<CheckAssetIdAndCapitalId, Object> {
@Autowired
private ContractInfoService contractInfoService;
private String[] fields;
@Override
public void initialize(CheckAssetIdAndCapitalId constraintAnnotation) {
this.fields = constraintAnnotation.fields();
}
@Override
public boolean isValid(Object object, ConstraintValidatorContext context) {
if (object == null) {
return true;
}
try {
String assetId = (String) getField(object, fields[0]);
String capitalId = (String) getField(object, fields[1]);
if(!contractInfoService.haveContract(capitalId,assetId)){
return false;
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
private Object getField(Object object, String fieldName) throws IllegalAccessException {
if (object == null) {
return null;
}
Class clazz = object.getClass();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
if (field.getName().equals(fieldName)) {
field.setAccessible(true);
return field.get(object);
}
}
return null;
}
}
网友评论