Using JPA in custom ConstraintValidator

I’m writing a spring boot application. I need to create a custom ConstraintValidator that read a relational database. I’m already using JPA inside the application.
The problem is that the Validator is created using new(), I suppose, therefore it is not aware of the spring context and therefore it is unable to access the EntityManager.
How can access it?
Any suggest?

Best regards


It’s a bit unfortunate Spring Boot doesn’t inject the constraint validators: we provide an API to do exactly that.

You can create the ValidatorFactory which is at the root of the HV validation process like this:

    .constraintValidatorFactory( new MyInjectionAwareConstraintValidatorFactory( mySpringContext ) )

And you cant then create your constraint validator and do the injection in your MyInjectionAwareConstraintValidatorFactory. MyInjectionAwareConstraintValidatorFactory should implement ConstraintValidatorFactory which is a very simple interface.

If I were you, I would suggest to the Spring Boot people to enable injection in the constraint validators using this mechanism.

I suppose you can override the creation of the ValidatorFactory in Spring Boot or at least tune it.