范围时间验证
/** * 范围时间验证注解 */@Target({ ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE, ElementType.TYPE_USE })@Retention(RetentionPolicy.RUNTIME)@Constraint(validatedBy = IntervalTimeCheckValidator.class)@Documented@Repeatable(IntervalTimeCheck.List.class)public @interface IntervalTimeCheck { String[] beginProps() default {"beginTime"}; String[] endProps() default {"endTime"}; String message() default "开始时间不能大于结束时间 "; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; @Target({ ElementType.TYPE,ElementType.FIELD,ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.RUNTIME) @Documented @interface List { IntervalTimeCheck[] value(); }}
public class IntervalTimeCheckValidator implements ConstraintValidator<IntervalTimeCheck, Object> { private String[] beginProps; private String[] endProps; @Override public void initialize(IntervalTimeCheck constraintAnnotation) { this.beginProps = constraintAnnotation.beginProps(); this.endProps = constraintAnnotation.endProps(); } @Override public boolean isValid(Object value, ConstraintValidatorContext context) { BeanWrapper beanWrapper = new BeanWrapperImpl(value); boolean valid = true; for (int i = 0; i < beginProps.length; i++) { String beginProp = beginProps[i]; String endProp = endProps[i]; Object beginObjVal = beanWrapper.getPropertyValue(beginProp); Object endObjVal = beanWrapper.getPropertyValue(endProp); if (ObjectUtils.isNotEmpty(beginObjVal) && ObjectUtils.isNotEmpty(endObjVal)) { int result = compareDateTime(beginObjVal, endObjVal); if (result < 0) { valid = false; break; } } } return valid; } private int compareDateTime(Object beginObjVal, Object endObjVal) { int result = 0; if (beginObjVal instanceof LocalDateTime) { LocalDateTime beginDateTime = (LocalDateTime) beginObjVal; LocalDateTime endDateTime = (LocalDateTime) endObjVal; result = endDateTime.compareTo(beginDateTime); } else if (beginObjVal instanceof LocalDate) { LocalDate beginDate = (LocalDate) beginObjVal; LocalDate endDate = (LocalDate) endObjVal; result = endDate.compareTo(beginDate); } else if (beginObjVal instanceof Date) { Date beginDate = (Date) beginObjVal; Date endDate = (Date) endObjVal; result = endDate.compareTo(beginDate); } return result; }}