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

谁都会走 提交于 2019-11-29 13:09:06
Gunnar

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