In our project we have Service and DAO layers in separate Maven modules. Service module depends on DAO module and works with it's entities. The problem is that we can't put custom jsr 303 constraint which uses some services from service layer in DAO entity because that would create the back reference from DAO layer to service layer, because the validator class needs to be referenced in validatedBy attribute of custom @Constraint.
Is there a way (using standard jsr 303 api) to specify validator class of some custom constraint at runtime (or solve our problem in any other way)? The built in constraints have empty validatedBy attribute, but I don't know if there is some api for that.
You may use an XML based constraint mapping to assign a validator to your constraint to avoid the reference from the annotation to the validator implementation.
The BV 1.1 EG is also discussing some improvements in that area. Feel free to weigh in on the issue on the mailing list.
We faced the same issue in our Spring based project. To solve it in best Spring way we split ConstraintValidator interface and implementation. For example in domain layer we only have interface:
In service layer we implement that interface:
Next we declare a bean in Spring Context for UniqueValidatorJpaImpl.
Finally to make all that staff working we extended SpringConstraintValidatorFactory. By default it only creates a new instance of class specified in validatedBy. We extended it by first looking in spring context for a bean of corresponding type: