2011-04-16 131 views
4

我有MethodInterceptor与依赖关系。我怎么注入它们?MethodInterceptor中的依赖注入

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

+1

你看到this.http://code.google.com/p/google-guice/issues/detail ID = 88 – 2011-04-16 09:12:08

+1

他们正在谈论生根粉样品here.http://code.google .com/p/google-guice/wiki/AOP#Injecting_Interceptors – 2011-04-16 09:13:14

+0

@ doc_180,我播种它。但是我错过了'requestInjection'。非常感谢。请将它作为答案发布。 – 2011-04-16 09:17:43

回答

10

Guice FAQ

为了注入依赖于AOP的MethodInterceptor,使用requestInjection()沿着标准bindInterceptor()调用。

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

如果'WeekendBlocker'在构造函数中有'@ Inject',我们该怎么做?理想情况下,我想要一个'newInstance(WeekendBlocker.class)'方法,其中WeekendBlocker之前使用bind(WeekendBlocker.class)绑定。 – joscarsson 2013-06-10 07:46:36