Bean Validation API / Hibernate Validator: any way to detect the requested validation groups during validation?

Viewed 35

Indeed, this is somewhat a duplicate of a previous question, however I was wondering whether, after nine years and some new specification versions being published, the situation has changed in any way, or whether at least a non portable way to solve this problem exists (I mean: does Hibernate Validator allow to do this, even if the API does not?).

The question is: is there a way I can make my custom constraint validator detect the validation groups that were passed to the validator instance causing the validation to occur, by inspecting the ConstraintValidatorContext?

Example, suppose I have my bean:

public class MyBean {

  @MyConstraint(value = 5, groups = V1.class)
  @MyConstraint(value = 10, groups = {V2.class, V3.class})
  private int foo;

  // cut
}

and a validator call:

validator.validateValue(MyBean.class, "foo", 7, V2.class);

can my constraint validator detect that V2.class validation group was requested, in this specific case?

public class MyConstraintValidator implements ConstraintValidator<MyConstraint, Integer> {

  // cut

  @Override
  public boolean isValid(Integer value, ConstraintValidatorContext context) {
    Class<?>[] requestedValidationGroups = // expected {V2.class} here, in case of the above call
  }
}

In the initialize method I can get an information about the static declaration of the constraint annotation, so in the above example I could get {V1.class} or {V2.class, V3.class} depending on which of the two constraints the implementation detects as the one being applied. However, I would need to get just {V2.class} in this case.

Is it possible in some way?

Looking at Hibernate Validator 6.0 sources, I see I would need access to org.hibernate.validator.internal.engine.ValueContext<T, V>, in particular its currentGroup property, but neither this group nor the ValueContext itself is passed to the Hibernate Validator constraint validator context implementation implementation (org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorContextImpl), whose creation, on the other hand, seems not to be customisable (there's a direct new ConstraintValidatorContextImpl(...) call in org.hibernate.validator.internal.engine.constraintvalidation.SimpleConstraintTree.validateConstraints(ValidationContext<T>, ValueContext<?, ?>, Set<ConstraintViolation<T>>)).

Any further hint?

0 Answers
Related