7

I want to use interceptors in a Java-SE application and I am using weld as CDI implementation and i'm testing this here:

The Main-Class:

 public static void main(String[] args) {

    WeldContainer weldContainer = new Weld().initialize();

    Service service = weldContainer.instance().select(Service.class).get();
    service.methodCall();
    service.methodCallNumberTwo();

}

The Service-Class:

  public class Service {

    @TestAnnotation
    public void methodCall(){

      System.out.println("methodCall...!");
      methodCallNumberTwo();

    }

    @TestAnnotation
    public void methodCallNumberTwo(){

      System.out.println("methodCallNumberTwo...!");

    }

 }

The Interceptor-Class:

 @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 the output:

 I'm the TestInterceptor of public void Service.methodCall()
 methodCall...!
 methodCallNumberTwo...!
 I'm the TestInterceptor of public void Service.methodCallNumberTwo()
 methodCallNumberTwo...!

My Questions

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!

Qri
  • 227
  • 3
  • 11
  • Possible duplicate of [Java CDI. Interceptor is only invoked in the first method call in a class](http://stackoverflow.com/questions/32129910/java-cdi-interceptor-is-only-invoked-in-the-first-method-call-in-a-class) – lucasvc Jul 25 '16 at 05:53

1 Answers1

5

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.

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.

LightGuard
  • 5,298
  • 19
  • 19
  • Is this in the CDI spec somewhere? I looked to find a reference to Interceptors only being called via the Proxy objects, but was unable to find anything in the spec. – Eric B. Jan 23 '19 at 20:05
  • I don't think it'll be in the spec. My guess would to take a look at the EJB spec and any of the other supporting specs. – LightGuard Jan 24 '19 at 17:04