Thanks to the work for HV-1497, done by @Marko Bekhta and @Guillaume Smet, we now have a {{HibernateConstraintValidator}} which provides us an {{initialize}} method that also takes a {{HibernateConstraintValidatorInitializationContext}} argument.
Which btw is great and I was waiting for something like this for years ;-) Why? Because, that addition allows us to easily pass a *_+ dynamic +_* payload to each new instance of a {{HibernateConstraintValidator}} - which for us was a major pain so far to do. Right now we could only get a static _static_ payload from the annotation. But now we could pass a dynamic _dynamic_ payload each time we call {{validator.validate()}}. E.g. in almost all applications we use HV we need to know the language or country of a user for the validation process - think of zip codes which differ for each country. With the current architecture of BV / HV this is basically impossible to achieve. That's why we used hacks like put the language / country (the "payload") into a {{ThreadLocal}} and retrieve the "payload" from that {{ThreadLocal}} inside the {{isValid}} method of a {{ConstraintValidator}}.
That's why I propose following addition the Hibernate Validator: {code:java} someValidator .unwrap(ValidatorImpl.class) .withDynamicConstraintValidatorInitializationPayload(payloadObject) .validate(objectToValidate) {code} Inside a {{HibernateConstraintValidator}} we can retrieve that payload like this: {code:java} public class MyFutureValidator implements HibernateConstraintValidator<MyFuture, Instant> {
private SomeType dynamicPayload;
@Override public void initialize(ConstraintDescriptor<MyFuture> constraintDescriptor, HibernateConstraintValidatorInitializationContext initializationContext) { this.dynamicPayload = initializationContext.getDynamicPayload(SomeType.class); }
@Override public boolean isValid(Instant instant, ConstraintValidatorContext constraintContext) { // Here I can use the dynamic payload now dynamicPayload.getSomeData(); //... } } {code}
This {{withDynamicConstraintValidatorInitializationPayload}} / {{getDynamicPayload}} approach is the same we already use to pass a Dynamic payload as part of ConstraintViolation: https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#section-dynamic-payload |
|