为什么我的自定义constraintValidator抛出空指针?

时间:2018-08-19 07:48:36

标签: java spring-mvc

我正在创建一个自定义ConstraintValidator,以验证从Spring表单输入时,我的JodaTime对象的小时数是否在某个窗口内。

我的注释:

@Target({ElementType.METHOD, ElementType.FIELD})
@Documented
@Constraint(validatedBy = InputHoursValidator.class)
@Retention(RetentionPolicy.RUNTIME)
public @interface InputHoursConstraint {
String message() default "";

Class<?>[] groups() default {};

Class<? extends Payload>[] payload() default {};

}

我的验证者

public class InputHoursValidator implements ConstraintValidator<InputHoursConstraint, DateTime> {
private static final DateTimeFormatter HOURS_TIME_FORMAT = DateTimeFormat.forPattern("hh:mma");
private static final String EARLIEST_START_TIME = "5:00pm";
private static final String LATEST_END_TIME = "4:00am";

@Override
public void initialize(InputHoursConstraint constraintAnnotation) {

}

@Override
public boolean isValid(DateTime value, ConstraintValidatorContext context) {
    return !value.isBefore(DateTime.parse(EARLIEST_START_TIME, HOURS_TIME_FORMAT))
            && !value.isAfter(DateTime.parse(LATEST_END_TIME, HOURS_TIME_FORMAT).plusDays(1));

}


}

还有带有注释的我的mojo

public class HoursTrackingForm {

@NotNull(message = "Please enter a valid time in AM or PM")
@DateTimeFormat(pattern = "hh:mma")
@InputHoursConstraint(message = "Start time was before 5:00pm or after 4:00am")
private DateTime startTime;

@NotNull(message = "Please enter a valid time in AM or PM")
@DateTimeFormat(pattern = "hh:mma")
@InputHoursConstraint(message = "End time was before 5:00pm or after 4:00am")
private DateTime endTime;

//getters and setters
}

对我来说一切正常,但是当我提交对象进行验证时,验证器中的DateTime始终为空。

1 个答案:

答案 0 :(得分:0)

我的问题有两个方面。

1)如果我测试的是空场景,即使发现一个错误,我也没有意识到所有约束仍然得到验证。因此,虽然不是null会导致验证错误,但是我的自定义约束仍然会抛出NPE。解决方案是删除@NotNull并在@InputHoursConstraint中进行检查。

2)在我的验证批注中,我在ElementType.TYPE中添加了ElementType.LOCAL_VARIABLE@Target,这似乎使其可以工作。仍在研究原因,因为根据我的理解,我只需要ElementType.FIELD