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)
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 ConstraintViolations 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With