Reputation: 1509
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?
Upvotes: 0
Views: 984
Reputation: 3386
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.
Upvotes: 1