开发者

Dependencies injection in MethodInterceptor

开发者 https://www.devze.com 2023-02-25 01:01 出处:网络
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.

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 inst开发者_运维技巧ances instead of classes.


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)));
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消