1.7 KiB
1.7 KiB
JAVAX Validation工具类
手动对对象进行验证
/**
* @author dss
* @since 2022/7/6
*/
public class ValidationUtil {
/**
* 开启快速结束模式 failFast (true)
*/
private static final Validator validator = Validation.byProvider(HibernateValidator.class).configure().failFast(false).buildValidatorFactory().getValidator();
/**
* 校验对象
*
* @param t bean
* @param groups 校验组
* @return ValidResult
*/
public static <T> void validateBean(T t,Class<?>...groups) {
if (t==null) throw new MyException(RestResponse.MSG.PARAM_VALIDATION_FAILURE);
Set<ConstraintViolation<T>> violationSet = validator.validate(t,groups);
boolean hasError = violationSet != null && !violationSet.isEmpty();
//存在验证错误直接抛出异常
if (hasError){
for (ConstraintViolation<T> violation : violationSet) {
throw new MyException(RestResponse.MSG.PARAM_VALIDATION_FAILURE).setMsg(violation.getMessage());
}
}
}
/**
* 校验bean的某一个属性
*
* @param obj bean
* @param propertyName 属性名称
* @return ValidResult
*/
public static <T> void validateProperty(T obj, String propertyName) {
Set<ConstraintViolation<T>> violationSet = validator.validateProperty(obj, propertyName);
boolean hasError = violationSet != null && !violationSet.isEmpty();
//存在验证错误直接抛出异常
if (hasError){
for (ConstraintViolation<T> violation : violationSet) {
throw new MyException(RestResponse.MSG.PARAM_VALIDATION_FAILURE).setMsg(violation.getMessage());
}
}
}
}