简体   繁体   中英

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.

I solved it by adding:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM