Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependencies injection in MethodInterceptor

I have MethodInterceptor with dependencies. How could I inject them?

Here, in 2007, Bob Lee said that this possibility should be included in next release, but I can't find API for this. bindInterceptor method requires instances instead of classes.

like image 298
Stan Kurilin Avatar asked Apr 16 '11 08:04

Stan Kurilin


1 Answers

From the Guice FAQ:

In order to inject dependencies in an AOP MethodInterceptor, use requestInjection() alongside the standard bindInterceptor() call.

public class NotOnWeekendsModule extends AbstractModule {
  protected void configure() {
    MethodInterceptor interceptor = new WeekendBlocker();
    requestInjection(interceptor);
    bindInterceptor(any(), annotatedWith(NotOnWeekends.class), interceptor);
  }
}

Another option is to use Binder.getProvider and pass the dependency in the constructor of the interceptor.

public class NotOnWeekendsModule extends AbstractModule {
  protected void configure() {
     bindInterceptor(any(),
         annotatedWith(NotOnWeekends.class),
         new WeekendBlocker(getProvider(Calendar.class)));
  }
}
like image 94
Jesse Wilson Avatar answered Sep 28 '22 09:09

Jesse Wilson