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.

2
  • Another reason why I think this API is flawed Commented Sep 30, 2013 at 7:15
  • 2
    just for completeness, this was answered here: stackoverflow.com/questions/26544588/… Commented Nov 22, 2016 at 10:21

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, so I can't leave the validatedBy for my constraint blank and expect Hibernate Validator to pick up my custom validator?
No, you must specify your custom validator in the annotation for Hibernate to find it.
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: docs.jboss.org/hibernate/stable/validator/reference/en-US/…
5

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.