【问题标题】:Dependencies injection in MethodInterceptorMethodInterceptor 中的依赖注入
【发布时间】:2018-03-20 05:24:49
【问题描述】:

我有带有依赖项的 MethodInterceptor。我怎么能注射它们?

Here,2007 年,Bob Lee 说下一个版本应该包含这种可能性,但我找不到用于此的 API。 bindInterceptor 方法需要实例而不是类。

【问题讨论】:

标签: java dependency-injection aop guice


【解决方案1】:

来自Guice FAQ

要在 AOP MethodInterceptor 中注入依赖项,请在标准 bindInterceptor() 调用旁边使用 requestInjection()

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

另一种选择是使用Binder.getProvider,并在拦截器的构造函数中传递依赖。

public class NotOnWeekendsModule extends AbstractModule {
  protected void configure() {
     bindInterceptor(any(),
         annotatedWith(NotOnWeekends.class),
         new WeekendBlocker(getProvider(Calendar.class)));
  }
}

【讨论】:

  • 如果WeekendBlocker在构造函数上有@Inject,我们怎么做?理想情况下,我想要一个方法 newInstance(WeekendBlocker.class),其中 WeekendBlocker 之前使用 bind(WeekendBlocker.class) 绑定。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-08
  • 2014-06-12
  • 2013-04-10
  • 2010-11-27
相关资源
最近更新 更多