Custom bean validation does not `@inject` CDI bean

2019-02-21 07:46发布

问题:

I am using GF4 with bean validation. I am trying to @Inject a service bean in my custom validator but I get a null value.

 public class TestValidator implements ConstraintValidator<>{
   @Inject Service myService;
}

Isn't this suppose to be working with JEE7?

Also, I am trying to find built-in dynamic message interpolation (Without writing my own MessageInterpolator). I did see some examples but they are not very clear. What I am looking for is to pass dynamic parameters from the ConstraintValidator.isValid. For example:

Message_test={value} is not valid

And somehow weave this, in the same way that you can statically interpolate the Annotation values e.g. size_msg={min}-{max} is out of range.

回答1:

Yes, dependency injection into validators should be possible with Java EE 7 / Bean Validation 1.1 in general.

How do you perform validation and how do you obtain a Validator object? Note that DI only works by default for container-managed validators, i.e. those you retrieve via @Inject or a JNDI look-up. If you bootstrap a validator yourself using the BV bootstrap API, this validator won't be CDI-enabled.

Regarding message interpolation, you can refer to the validated value using ${validatedValue}. If you're working with Hibernate Validator 5.1.0.Alpha1 or later, then you also have the possibility to add more objects to the message context from within ConstraintValidator#isValid() like this:

public boolean isValid(Date value, ConstraintValidatorContext context) {
    Date now = GregorianCalendar.getInstance().getTime();

    if ( value.before( now ) ) {
        HibernateConstraintValidatorContext hibernateContext =
                context.unwrap( HibernateConstraintValidatorContext.class );

        hibernateContext.disableDefaultConstraintViolation();
        hibernateContext.addExpressionVariable( "now", now )
                .buildConstraintViolationWithTemplate( "Must be after ${now}" )
                .addConstraintViolation();

        return false;
    }

    return true;
}