1 Reply Latest reply on Dec 2, 2009 5:00 AM by galder.zamarreno

    Injection into the custom interceptor

    skabashnyuk

      I have a question about using custom interceptors.
      Is it possible to inject object into the custom interceptor using
      @Inject annotation?
      My interceptor code look like this:

      public class MyInterceptor extends CommandInterceptor
      {
      
       ......
       @Inject
       public void inject(InterceptorParameter interceptorParameter)
       {
       .....
       }
       ....
      }


      InterceptorParameter class defined as :

      @NonVolatile
      public class InterceptorParameter
      {
       ...
      }


      Interceptor configured from xml:

      <customInterceptors>
       <interceptor after="org.jboss.cache.interceptors.CacheStoreInterceptor"
       class="org.exoplatform.services.jcr.impl.storage.jbosscache.MyInterceptor" >
       </interceptor>
      </customInterceptors>


      Interceptor parameter registered through CacheSPI.

      Cache<Serializable, Object> cache =
       factory.createCache(InjectionTest.class.getResourceAsStream("test-custom-interceptor.xml"),
      false);
      
      InterceptorParameter interceptorParameter = new InterceptorParameter();
      ((CacheSPI<Serializable,
      Object>)cache).getComponentRegistry().registerComponent(interceptorParameter,InterceptorParameter.class);
      
      cache.create();
      cache.start();
      



      Thanks.

        • 1. Re: Injection into the custom interceptor
          galder.zamarreno

          That looks pretty hacky. You shouldn't be fiddling with the component registry.

          Looks to me the following would be much simpler to do:

          public class MyInterceptor extends CommandInterceptor {
           private final InterceptorParameter ip;
           public MyInterceptor(InterceptorParameter ip) {
           this.ip = ip;
           }
          }

          And then do:
          InterceptorParameter ip = new InterceptorParameter();
          MyInterceptor mi = new MyInterceptor(ip);
          ((CacheSPI<Serializable, Object>)cache).addInterceptor(mi, org.jboss.cache.interceptors.CacheStoreInterceptor.class);

          Bottom line, if your interceptor does not take any parameters, use the XML way to configure the interecetor. Otherwise, use the programatic way of shown in this comment.

          Another benefit of the approach I suggested is that InterceptorParameter in MyInterceptor becomes final and so, baring other params or exposure of InterceptorParameter, MyInterceptor becomes immutable, which is a good programming practice.

          You can find examples like this and more in the JBoss Cache testsuite :)