为什么拦截器不在同一服务类中调用? [英] Why is the interceptor not called in the same service class?
问题描述
我想在Java-SE应用程序中使用拦截器,我使用焊接作为CDI实现,我在这里测试:
I want to use interceptors in a Java-SE application and I am using weld as CDI implementation and i'm testing this here:
主要 - 类:
public static void main(String[] args) {
WeldContainer weldContainer = new Weld().initialize();
Service service = weldContainer.instance().select(Service.class).get();
service.methodCall();
service.methodCallNumberTwo();
}
服务级别:
public class Service {
@TestAnnotation
public void methodCall(){
System.out.println("methodCall...!");
methodCallNumberTwo();
}
@TestAnnotation
public void methodCallNumberTwo(){
System.out.println("methodCallNumberTwo...!");
}
}
拦截器类:
@Interceptor
@TestAnnotation
public class TestInterceptor {
@AroundInvoke
public Object interceptorMethod(InvocationContext invocationContext) throws Exception {
System.out.println("I'm the TestInterceptor of "+invocationContext.getMethod());
return invocationContext.proceed();
}
}
Aaaand输出:
I'm the TestInterceptor of public void Service.methodCall()
methodCall...!
methodCallNumberTwo...!
I'm the TestInterceptor of public void Service.methodCallNumberTwo()
methodCallNumberTwo...!
我的问题
第一:为什么在我调用methodCallNumberTwo()时没有在methodCall()中调用拦截器?
First: Why isn't the interceptor called in methodCall() when i'm calling methodCallNumberTwo()?
第二:有没有办法改变它?
Second: Is there a way to change that?
我只是研究拦截器的行为并想了解。提前谢谢!
I'm only studying the behavior of interceptors and want to understand. Thank you in advance!
推荐答案
因为您在对象的同一实例上调用拦截器,所以不会调用拦截器。如果您熟悉EJB,则与在同一对象上调用方法而不是通过EJB上下文相同。
The interceptor is not called because you are calling it on the same instance of the object. If you're familiar with EJBs it's the same as calling a method on the same object instead of through the EJB context.
如果你通过它进行调试,你会注意到对注入对象的方法调用是通过代理进行的。从methodOne到methodTwo的方法调用未被代理。
If you debug through it you'll notic that the method call on the injected objects goes through a proxy. The method call from methodOne to methodTwo isn't proxied.
这篇关于为什么拦截器不在同一服务类中调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!