0

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.

Ioannis Deligiannis
  • 2,679
  • 5
  • 25
  • 48

1 Answers1

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;
}
Mr Lister
  • 45,515
  • 15
  • 108
  • 150
Gunnar
  • 18,095
  • 1
  • 53
  • 73
  • Thanks for your answer. I am using `@Named @ApplicationScoped` to define my services. Validation is triggered through JSF 2.2, so I assume it would be loaded via CDI. Inside my validator, I am using `@Inject` to reference my service bean. As far as hibernate is concerned, I wouldn't like to couple my application to any implementation. – Ioannis Deligiannis Nov 25 '13 at 20:10
  • I managed to resolve the issue. If the Validation annotation is set on a JSF bean, then the service is injected properly. If validation annotation is set on the JPA bean, then it is not. I assume this is normal because the services are defined as `@Named/@ApplicationScoped` so they are not available in the hibernate CDI context. – Ioannis Deligiannis Nov 30 '13 at 14:56