工具類:
public class ValidationUtils {
private static final Validator validator;
static {
validator = Validation.buildDefaultValidatorFactory().getValidator();
}
/**
* 校驗物件
*
* @param object 待校驗物件
* @param groups 待校驗的組
* @throws BizException 校驗不透過,則報業務異常
*/
public static void validateEntity(Object object, Class<?>... groups) throws IllegalArgumentException {
Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
if (!constraintViolations.isEmpty()) {
String msg = constraintViolations.stream().map(ConstraintViolation::getMessage).collect(Collectors.joining("||"));
throw new IllegalArgumentException(msg);
}
}
}
使用工具類