简介
说明
本文介绍手动校验@NotBlank、@NotNull等的工具类。
使用场景:controller接口的入参很多,需要他人提供,但他人提供的类的字段很多,字段都没有加@NotNull等注解;而且这个类以后很可能再变动。
解决方案:写一个中间类,将入参转换为中间类,在中间类的字段上加@NotBlank等注解,然后用本工具手动校验它。
优点
利用@NotBlank等校验,方便快捷
相关网址(详细用法)
SpringBoot--用hibernate validator手动校验--方法/实例_IT利刃出鞘的博客springboot 手动校验
代码
package com.knife.common.util;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidationException;
import javax.validation.Validator;
import java.util.Set;
/**
* hibernate validator的校验工具
*/
public class ValidateUtil {
private static final Validator validator =
Validation.buildDefaultValidatorFactory().getValidator();
/**
* 校验实体类
*/
public static <T> void validate(T t) {
Set<ConstraintViolation<T>> constraintViolations = validator.validate(t);
if (constraintViolations.size() > 0) {
StringBuilder validateError = new StringBuilder();
for (ConstraintViolation<T> constraintViolation : constraintViolations) {
validateError.append(constraintViolation.getMessage()).append(";");
}
throw new ValidationException(validateError.toString());
}
}
/**
* 通过组来校验实体类
*/
public static <T> void validate(T t, Class<?>... groups) {
Set<ConstraintViolation<T>> constraintViolations = validator.validate(t, groups);
if (constraintViolations.size() > 0) {
StringBuilder validateError = new StringBuilder();
for (ConstraintViolation<T> constraintViolation : constraintViolations) {
validateError.append(constraintViolation.getMessage()).append(";");
}
throw new ValidationException(validateError.toString());
}
}
}
用法
User user = new User();标签:constraintViolations,SpringBoot,--,import,校验,NotNull,new,validate,validateError From: https://blog.51cto.com/knifeedge/5729943
//对user字段赋值
ValidateUtil.validate(user);