Skip to content
Advertisement

Java NullPointer Custom Validator javax.validation.ConstraintValidator

I have the following Validator that I use to validate an Update Request.

@Component
public class UpdateDateValidator implements ConstraintValidator<ValidateDateCreditor, BasicUpdateRequest> { 

    @Autowired
    private CreditorRepository creditorRepository;  

    @Override
    public boolean isValid(BasicUpdateRequest object, ConstraintValidatorContext constraintValidatorContext) {          
                                        
        Creditor creditor = creditorRepository.findById(object.getIdCreditor()).orElseThrow(() -> new NoSuchElementException(Constants.ELEMENT_NOT_FOUND_MSG + ": CREDITOR"));
                    
        if (creditor.getDateDeadline() == null 
                || UtilityDate.compareDateNoTime(object.getDateDeadline(), creditor.getDateDeadlineConvention()) <= 0) {
            return true;
        }
    
        return false;
    }

}

object.getIdCreditor() has a value, but the execution of the findById method “creditorRepository.findById(object.getIdCreditor())” goes into NullPointer exception

I don’t understand what’s wrong.

Advertisement

Answer

I solved it by adding:

@Override
public void initialize(ValidateDateCreditor constraintAnnotation) {
    ConstraintValidator.super.initialize(constraintAnnotation);
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement