Custom bean validation does not `@inject` CDI beans and does not interpolate message?

做~自己de王妃 提交于 2019-12-18 07:24:41

问题


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;
}


来源:https://stackoverflow.com/questions/20161837/custom-bean-validation-does-not-inject-cdi-beans-and-does-not-interpolate-mes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!