Validate验证工具

针对一些业务校验不能放在@Controller层注解校验

可以支持个性化分组校验

@Autowired
private Validator validator;

BeanValidatorsUtils.validateWithException(validator,basicInfoVO,XCAuthBasicInfoVO.authBasic.class);
public class BeanValidatorsUtils {

    public BeanValidatorsUtils() {
    }

    public static void validateWithException(Validator validator, Object object, Class... groups) throws ConstraintViolationException {
        Set constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            throw new ConstraintViolationException(constraintViolations);
        }
    }

    public static List extractMessage(ConstraintViolationException e) {
        return extractMessage(e.getConstraintViolations());
    }

    public static List extractMessage(Set constraintViolations) {
        List errorMessages = Lists.newArrayList();
        Iterator i$ = constraintViolations.iterator();

        while (i$.hasNext()) {
            ConstraintViolation violation = (ConstraintViolation) i$.next();
            errorMessages.add(violation.getMessage());
        }

        return errorMessages;
    }

    public static Map extractPropertyAndMessage(ConstraintViolationException e) {
        return extractPropertyAndMessage(e.getConstraintViolations());
    }

    public static Map extractPropertyAndMessage(Set constraintViolations) {
        Map errorMessages = Maps.newHashMap();
        Iterator i$ = constraintViolations.iterator();

        while (i$.hasNext()) {
            ConstraintViolation violation = (ConstraintViolation) i$.next();
            errorMessages.put(violation.getPropertyPath().toString(), violation.getMessage());
        }

        return errorMessages;
    }

    public static List extractPropertyAndMessageAsList(ConstraintViolationException e) {
        return extractPropertyAndMessageAsList(e.getConstraintViolations(), " ");
    }

    public static List extractPropertyAndMessageAsList(Set constraintViolations) {
        return extractPropertyAndMessageAsList(constraintViolations, " ");
    }

    public static List extractPropertyAndMessageAsList(ConstraintViolationException e, String separator) {
        return extractPropertyAndMessageAsList(e.getConstraintViolations(), separator);
    }

    public static List extractPropertyAndMessageAsList(Set constraintViolations, String separator) {
        List errorMessages = Lists.newArrayList();
        Iterator i$ = constraintViolations.iterator();

        while (i$.hasNext()) {
            ConstraintViolation violation = (ConstraintViolation) i$.next();
            errorMessages.add(violation.getPropertyPath() + separator + violation.getMessage());
        }

        return errorMessages;
    }
}

你可能感兴趣的:(Validate验证工具)