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)));
}
}
精彩评论