工具类
package com.common;
import com.common.SysException;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;
import java.util.stream.Collectors;
/**
1. @author: 0i77
3. @Description: 对象参数验证工具, 解决非controller层数据校验问题, @Validated、@Valid
*/
public class ValidationUtils {
private static final Validator validator;
static {
validator = Validation.buildDefaultValidatorFactory().getValidator();
}
/**
* 校验对象
*
* @param object 待校验对象
* @param groups 待校验的组
* @throws SysException 校验不通过,则报业务异常
*/
public static void validateEntity(Object object, Class<?>... groups) {
Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
if (!constraintViolations.isEmpty()) {
String msg = constraintViolations.stream().map(ConstraintViolation::getMessage).collect(Collectors.joining("||"));
throw new SysException(AppErrorCode.MESSAGE_NULL, msg);
}
}
}
参数校验具体测试
实体类中使用 @Validated、@Valid 注解即可实现