0

I have a custom annotation @UniqueModel, which is validated by a ConstraintValidator:

@Component
public class UniquePlaceValidator implements ConstraintValidator<UniqueModel, Model> {

    @Autowired
    private ModelRepository repository;

    public UniqueModelValidator() {
    }

    public void initialize(UniqueModel constraint) {
    }

    @Override
    public boolean isValid(Model model, ConstraintValidatorContext context) {
        if (repository == null)
            return true;

        Model dbModel = repository.findByNameAndMail(model.getName(), model.getMail());
        return dbModel == null;
    }

The problem is, that I need to do the validation before the safe()-method of the repository is called, otherwise the field injection won't work.

I therefor created a delegate-method with a @Valid-annotation, in order to force the unique-validation before:

Model save(@Valid Model model {
        return repository.save(model);
    }

Unfortunately this doesn't work, it seems like the @Valid-annotation is ignored by Spring.

How can I assure the correct timing of validation?

2
  • Can't you stackoverflow.com/questions/8820067/… ? Commented Aug 21, 2017 at 11:46
  • Can you post your spring configuration as well? Having just the bean validation constraints is not enough. You might need to do additional configuration. Commented Aug 21, 2017 at 12:08

1 Answer 1

1

Depending on your Bean validation configuration you may need to annotate your repository bean with @ValidateOnExecution.
But I'm not sure if Spring does support this annoation (see SPR-10641) hence I'm using Spring's own @Validated annotation in my repository and service interfaces and method level validation works fine!
See also this question and have a look into MethodValidationPostProcessor which clearly states "Target classes with such annotated methods need to be annotated with Spring's @Validated annotation at the type level". So it seems to be pretty clear that you have to use @Validated instead of @ValidateOnExecution until SPR-10641 is fixed.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.