Home > Net >  Java NullPointer CustomValidator javax.validation.ConstraintValidator
Java NullPointer CustomValidator javax.validation.ConstraintValidator

Time:03-12

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.

CodePudding user response:

I solved it by adding:

@Override
public void initialize(ValidateDateCreditor constraintAnnotation) {
    ConstraintValidator.super.initialize(constraintAnnotation);
}
  • Related