23

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.

Tom Tucker
  • 11,676
  • 22
  • 89
  • 130

3 Answers3

13

Those built-in are treated in special implementation-specific way and their validators are configured programmatically.

For Hibernate Validator it's done in ConstraintHelper.java. I think you can't achieve the same for your custom constraints.

axtavt
  • 239,438
  • 41
  • 511
  • 482
  • Thanks, so I can't leave the validatedBy for my constraint blank and expect Hibernate Validator to pick up my custom validator? – Tom Tucker Dec 22 '10 at 19:35
  • 3
    No, you must specify your custom validator in the annotation for Hibernate to find it. – Guillaume Dec 22 '10 at 19:39
  • 3
    Nowadays you can decouple the constraint definition (interface) and the validator itself, leaving the validatedBy empty, and making Hibernate to locate the validator using for example the ServiceLoader: https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#_constraint_definitions_via_code_serviceloader_code – Aníbal Feb 14 '22 at 16:01
1

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).

Aníbal
  • 785
  • 8
  • 24