【问题标题】:Are EJB method parameters validated automatically in a Java EE container?EJB 方法参数是否在 Java EE 容器中自动验证?
【发布时间】:2021-03-07 20:40:08
【问题描述】:

我是 Java Bean 验证的新手,所以我想了解它是如何工作的。
据我所知,在 Java EE 容器中,持久性提供程序使用 JPA 负责实体的验证,因此无需使用 Validator 以编程方式进行。
EJB 方法参数是否也会自动验证?

如果我有一个由 EJB 实现的 @Local 接口:

@Local
public interface ExampleLocal
{
    void doSomething(@NotNull String param);
}

我将null传递给上述方法:

public class Foo 
{
    @EJB
    private ExampleLocal example;

    public void callDoSomething()
    {
        example.doSomething(null);
    }
}

EJB 是否抛出 EJBException?

【问题讨论】:

    标签: jakarta-ee ejb bean-validation


    【解决方案1】:

    EJB 方法参数似乎没有自动验证。
    我在 TomEE 中进行了测试,我必须使用 Interceptor 来验证它们

    @Interceptor
    @Validable
    public class ValidationInterceptor
    {
        @Resource
        private Validator validator;
        
        @AroundInvoke
        private Object validate(InvocationContext ic) throws Exception
        {
            ExecutableValidator exVal = validator.forExecutables();
            Set<ConstraintViolation<Object>> violations =  exVal.validateParameters(ic.getTarget(),ic.getMethod(),ic.getParameters());
            if (!violations.isEmpty())
                throw new ConstraintViolationException(violations);
            return ic.proceed();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-02
      • 2011-04-25
      • 2018-10-28
      • 2011-01-17
      • 2012-06-07
      • 1970-01-01
      • 1970-01-01
      • 2019-07-08
      相关资源
      最近更新 更多