Reputation: 175
I have a problem to combine the javax annotation with custom ConstraintValidators.
I have an example class Person, where the name and the age are required.
@PersonConstraint
public class Person {
@NotNull
private String name;
@NotNull
private Integer age;
...
}
And I have an additional constraint:
@Constraint(validatedBy = PersonValidator.class)
@Target(TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface PersonConstraint{
String message() default "...";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
For the custom Validator:
public class PersonValidator implements ConstraintValidator<PersonConstraint, Person> {
...
@Override
public boolean isValid(Person value, ConstraintValidatorContext context) {
if(value.getAge() < 18)
return false;
...
}
}
When a Person object is validated now and the age is null, I got a Nullpointer Exception in the PersonValidator. I thoguht, this is something, which is checked by the javax Annoation @NotNull. Is there a solution to combine the annotations with the custom validators or do I have to check the null values in the validor by myself?
(The code is just an example - but this is a general question)
Upvotes: 3
Views: 2938
Reputation: 19129
Unless you are working with the group and group sequences, there is no guaranteed order in which constraints are going to be evaluated. You cannot rely in your custom constraint that the @NotNull
already has occured. And even it it had you would still get a NullPointerException
. Bean Validation will per default not stop after the first constraint violation, but collect all violations of a required validation (hence a set of ConstraintViolation
s are returned. So there might actually be already a constraint violation for age
, but in your custom ConstraintValidator
you would still be accessing a null
value. You cannot get around doing a null
check at this stage.
Upvotes: 2