自定义bean验证不是`@ inject` CDI bean,并且不插值消息吗? [英] Custom bean validation does not `@inject` CDI beans and does not interpolate message?

查看:92
本文介绍了自定义bean验证不是`@ inject` CDI bean,并且不插值消息吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有bean验证的GF4.我试图在自定义验证器中@Inject一个服务bean,但得到一个null值.

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

这不是应该与JEE7一起使用吗?

Isn't this suppose to be working with JEE7?

此外,我正在尝试查找内置的动态消息插值(不编写自己的MessageInterpolator).我确实看到了一些示例,但它们不是很清楚.我正在寻找的是从ConstraintValidator.isValid传递动态参数.例如:

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 = {值}无效

Message_test={value} is not valid

以某种方式编织它,就像您可以静态内插Annotation值一样,例如size_msg = {min}-{max}超出范围.

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.

推荐答案

是的,通常应该使用Java EE 7/Bean Validation 1.1将验证器中的依赖项注入.

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

如何执行验证以及如何获取Validator对象?请注意,默认情况下,DI仅适用于容器管理的验证器,即通过@Inject或JNDI查找检索的验证器.如果您使用BV引导API自己引导验证程序,则该验证程序将不会启用CDI.

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.

关于消息插值,您可以使用${validatedValue}引用已验证的值.如果您使用的是Hibernate Validator 5.1.0.Alpha1或更高版本,那么您还具有

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

这篇关于自定义bean验证不是`@ inject` CDI bean,并且不插值消息吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆