Quick revision
The short answer
Spring can inject the repository, because its LocalValidatorFactoryBean creates ConstraintValidator instances through Spring's bean factory, so constructor injection just works. But it is usually not a good idea: the validator hides a database query inside an annotation, it can run many times per request, and the existence check is better done in the service, where it gives a clear not-found error inside the transaction. If we keep it, we make it cheap, for example with one batched query or a cache, and we test it.
What to remember
In this answer, we saw that Spring injects dependencies into ConstraintValidator instances because LocalValidatorFactoryBean creates them through the bean factory, but that a repository call in a validator hides a query, can run many times per request and outside Spring, and guarantees nothing without the transaction and foreign key. An existence check belongs in the service, where it is visible and gives a clear error; if we keep a validator, we make it cheap with caching or batching and test it.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Spring can inject the repository, because its LocalValidatorFactoryBean creates ConstraintValidator instances through Spring's bean factory, so constructor injection just works. But it is usually not a good idea: the validator hides a database query inside an annotation, it can run many times per request, and the existence check is better done in the service, where it gives a clear not-found error inside the transaction. If we keep it, we make it cheap, for example with one batched query or a cache, and we test it.
Why this question is asked
A constraint like @ExistingCustomer on a customerId field looks elegant: the controller stays clean and invalid ids are rejected with the other field errors. Many teams try it, and many later remove it after finding slow requests, surprising queries in logs or validators that break outside Spring. Interviewers ask this as a scenario because the technical part is easy and the judgment is what matters. In this answer, we will see how Spring injects dependencies into validators, write the validator, look at the hidden costs, move the check into the service, and finish with how to keep the validator responsibly if we decide to.
1How Spring Injects Into a ConstraintValidator
Normally the validation provider creates validator instances itself, using a ConstraintValidatorFactory. Spring Boot configures validation with LocalValidatorFactoryBean, which installs Spring's own factory, SpringConstraintValidatorFactory. That factory asks the application context's bean factory to create each validator, so it is constructed like a bean, with constructor injection and @Autowired support, even though the validator class itself is not annotated with @Component.
6 messages in order. Play them, or step through them one at a time.
So the answer to how does Spring inject it is: through the validator factory, automatically, as long as the validator is created by the Spring-managed factory. That last condition is the first catch. A validator created by Validation.buildDefaultValidatorFactory() in a plain unit test, or by a validation factory that JPA builds for itself to validate entities before persisting, uses a factory that knows nothing about Spring, cannot call the constructor with arguments and fails. Whether Hibernate uses Spring's factory for entity validation depends on configuration, so check your setup before putting such a constraint on an entity.
2The Hidden Costs
The first cost is visibility. Someone reading the controller sees an annotation, not a database call. When the request is slow, the query does not appear where people look for it, and when the database is down, a validation step fails with a data access exception that the validation error handling never expected.
The second cost is repetition. Validation can run more than once for the same object: in the controller, again through @Validated on a service method, and again when JPA validates an entity carrying the same annotation. And inside collections it runs per element: an order import with List<@Valid LineRequest> of 500 lines, each with @ExistingProduct, issues 500 queries before our code starts.
The third cost is correctness. The check runs before the transaction that uses the result. The customer can be deleted between validation and saving, so the validator does not really guarantee anything; the foreign key in the database does. The validator only gives a nicer error for the common case.
3Doing the Check in the Service Instead
An existence check is a business rule with context: it needs the database and it belongs with the code that uses the customer. In the service, we load the customer we are going to use anyway, inside the transaction, so the check costs nothing extra.
Notice the gains. The query is visible and runs once, the customer it loads is the one we use, the transaction and the foreign key together make the result reliable, and the error is clear and can still point to the customerId field. The DTO keeps only shape rules like @NotNull, which work in any context, including plain unit tests without Spring.
4If We Keep the Validator
There are cases where a validator with a dependency is reasonable: a check against reference data that rarely changes, such as supported country codes loaded from a table, or a team convention where all reference checks report as field errors. Then we keep it cheap and predictable. The lookup should hit a cache, for example a Spring @Cacheable method holding the small set of valid codes, not the database on every call. For collections, a class-level constraint on the whole request can check all ids with one query, such as findAllById, instead of one per element. The validator must be stateless and safe to call concurrently. And we test it twice: a unit test that passes a mock repository to the constructor, and an integration test through Spring's validator that proves injection works and counts the queries for a request with many elements.
5Follow-up questions
Does injection work for validators used in method validation with @Validated?
Yes. Spring Boot's MethodValidationPostProcessor uses the same Spring-configured validator, so constraints on service method parameters get injected validators too. The concerns about hidden queries and repeated runs apply even more there, because the same object may be validated at both the controller and the service.
What happens if the repository throws during validation?
The exception propagates out of the validation call, wrapped by the provider in a ValidationException, so the client typically gets a 500 instead of a 400 or a clean 503. That is another reason to keep infrastructure calls in the service, where error handling and retries are designed for them.
Is it ever right to check uniqueness in a validator, such as an email not yet taken?
Only as a friendly early warning. Two requests can pass the check at the same moment and both insert the same email, so the unique index in the database is the real guard, and the service must still handle the constraint violation and map it to 409.
6Conclusion
In this answer, we saw that Spring injects dependencies into ConstraintValidator instances because LocalValidatorFactoryBean creates them through the bean factory, but that a repository call in a validator hides a query, can run many times per request and outside Spring, and guarantees nothing without the transaction and foreign key. An existence check belongs in the service, where it is visible and gives a clear error; if we keep a validator, we make it cheap with caching or batching and test it.
Open with
Technically it works. Spring Boot sets up validation with LocalValidatorFactoryBean, which uses SpringConstraintValidatorFactory, so validators are created through the bean factory and constructor injection of a repository just works, without annotating the validator as a component.
Then, if they want more
But I would usually not do it. The annotation hides a database query: someone reading the controller sees @ExistingCustomer, not a SELECT. Validation can run several times, at the controller, at a @Validated service and maybe on the entity, and inside lists it runs per element, so 500 lines means 500 queries.
Outside Spring, for example in a plain unit test or a validator factory that JPA builds for itself, the validator cannot even be created. And it guarantees nothing, because the customer can be deleted between validation and the save; the foreign key is the real guard.
So I would do the existence check in the service, inside the transaction, by loading the customer we need anyway and throwing a clear not-found or unknown-reference error that the exception handler maps to 422 or 400 with the field name.
If the team still wants a validator, for example for rarely changing reference data, I would make it cheap with a cache or one batched query for all ids, keep it stateless, and test both the logic and the injection and query count.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring Framework reference, Spring Web MVC
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "A custom validator needs a repository to check that a customer id exists. Is that a good...": https://scrivio-interview-library.netlify.app/spring-boot/request-validation/cf79d471fe/