Java CDI。拦截器仅在类的第一个方法调用中被调用 [英] Java CDI. Interceptor is only invoked in the first method call in a class

查看:93
本文介绍了Java CDI。拦截器仅在类的第一个方法调用中被调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用CDI拦截器,并且我意识到只有被@Interceptor注释的类中的第一个方法调用才会被拦截。在下面的示例中,methodB永远不会被拦截。

I'm using CDI Interceptors and I've realized that only the first method call in a class annotated with @Interceptor is intercepted. In the example below methodB is never intercepted.

@InterceptorBinding
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Transactional {

}


@Transactional
@Interceptor
public class TransactionsInterceptor {

    @AroundInvoke
    public Object transactionInterceptor(InvocationContext context) throws Exception {

          System.out.println("Method="+context.getMethod().getName());
          return context.proceed();

    }
}


public Interface AnImportantInterface {
      public void methodA();
      public void methodB();
}

@Transactional
@ThreadScoped
public class AnImportantClass implements AnImportantInterface {

    public void methodA() {

        methodB();
    }

    public void methodB() {

        //This method is never intercepted
    }

}


public class AnotherImportantClass {
    @Inject AnImportantInterface aui;

    public void someMethod() {
        aui.methodA();
    }
}

如果methodA是先叫?有什么解决方法吗?

How can I achieve that methodB be intercepted if methodA is called first? is there some workaround?

推荐答案

这是因为您正在调用 methodB()直接,而不是通过CDI代理,因此永远不会调用拦截器。拦截器仅在使用其代理调用CDI bean方法时被调用。您应该将方法B移到另一个CDI bean中,然后将其 @Inject 移到该CBean中,然后从 methodA 更改 methodB() bean2.methodB(..)

It's because you are calling methodB() directly and not via the CDI proxy so the interceptor is never invoked. Interceptors will only be invoked when the CDI bean method is called using its proxy. You should move method B into another CDI bean and @Inject it into this one and from methodA change methodB() to bean2.methodB(..).

这篇关于Java CDI。拦截器仅在类的第一个方法调用中被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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