'Empty validatedBy in @Constraint
I noticed that all built-in constraints have an empty value for the validatedBy parameter in @Constraint. i.e. @Constraint(validatedBy = {})
First, why are they allowed to have an empty value for validatedBy? I thought you can leave it blank only for constraint composition that does not need addtional validation?
Also, note that the Hibernate Validator can still find a validator implementation class for each built-in constraint, despite the validatedBy is empty, but if I leave the validatedBy blank for my constraint, my custom validator never gets picked up. Why is that?
Thanks.
Solution 1:[1]
Maybe have a look at this answer:
How to avoid cross dependency between layers because of @Constraint validatedBy?
And those two links:
Adding constraints programmatically: http://docs.jboss.org/hibernate/stable/validator/reference/en-US/html/validator-specifics.html#section-programmatic-api
Adding constraints per xml: http://docs.jboss.org/hibernate/validator/4.1/reference/en-US/html/validator-xmlconfiguration.html
Solution 2:[2]
Nowadays there are several methods to decouple the interface with the constraint definition and the validator, so you can have them in different layers and leave the validatedBy attribute empty. One of the simplest is using Hibernate ServiceLoader adding the validator classes in a /META-INF/services/javax.validation.ConstraintValidator file in resources folder (changed to jakarta.validation.ConstraintValidator with Hibernate 7).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Community |
| Solution 2 | AnĂbal |
