import javax.validation.Constraint; import javax.validation.Payload; import java.lang.annotation.*; /** * @author cr 2020-04-21 校验结束时间大于等于开始时间 */ @Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE, ElementType.TYPE_USE}) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = CheckTimeIntervalValidation.class) @Documented @Repeatable(CheckTimeInterval.List.class) public @interface CheckTimeInterval { String beginTime() default "from"; String endTime() default "to"; String message() default "{org.hibernate.validator.referneceguide.chapter06.CheckCase.message}"; 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 { CheckTimeInterval[] value(); } }
import com.dahuatech.creditcloud.util.DateUtil; import com.dahuatech.creditcloud.util.StrUtils; import org.springframework.beans.BeanWrapper; import org.springframework.beans.BeanWrapperImpl; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import java.util.Date; /** * @author cr 2020-04-21 校验结束时间大于等于开始时间 */ public class CheckTimeIntervalValidation implements ConstraintValidator<CheckTimeInterval, Object> { private String beginTime; private String endTime; @Override public void initialize(CheckTimeInterval constraintAnnotation) { this.beginTime = constraintAnnotation.beginTime(); this.endTime = constraintAnnotation.endTime(); } @Override public boolean isValid(Object value, ConstraintValidatorContext context) { BeanWrapper beanWrapper = new BeanWrapperImpl(value); String begin = StrUtils.convertString(beanWrapper.getPropertyValue(beginTime)); String end = StrUtils.convertString(beanWrapper.getPropertyValue(endTime)); if (begin.isEmpty() || end.isEmpty()) { return true; } Date d1 = DateUtil.dateParse(begin); Date d2 = DateUtil.dateParse(end); if (null == d1 || null == d2) { return false; } int result = d2.compareTo(d1); return result >= 0; } }