在 Guice 中注入方法拦截器

Injecting method interceptors in Guice

我在网上搜索了它,每个人(包括)google 建议使用 requestInjection(),但我仍然不明白如何使用它。我有一个实现方法拦截器的 class:

public class CacheInterceptor implements MethodInterceptor {
    private ILocalStore localStore;
    private IRemoteStore remoteStore;
    private CacheUtils cacheUtils;

    public CacheInterceptor() {
    }
   @Inject
    public CacheInterceptor(ILocalStore localStore, CacheUtils cacheUtils, IRemoteStore remoteStore) {
    this.localStore = localStore;
    this.cacheUtils = cacheUtils;
    this.remoteStore = remoteStore;
    }
}

我有 3 个 class 扩展 AbstractModule.

public class CacheUtilModule extends AbstractModule {
    @Override
    protected void configure() {
        bind(CacheUtils.class);
    }
}

public class LocalCachingModule extends AbstractModule {
    @Override
    public void configure() {
        bind(ILocalStore.class).to(LocalStore.class);
    }
}

public class RedisCachingModule extends AbstractModule {
    @Override
    protected void configure() {
        bind(IRemoteStore.class).to(RemoteStore.class);
    }
}

我做了以下绑定拦截器

public class RequestScopedCachingModule extends AbstractModule {

    @Override
    public void configure() {
        install(new CacheUtilModule());
        install(new LocalCachingModule());
        install(new RedisCachingModule());
        MethodInterceptor interceptor = new CacheInterceptor();
        requestInjection(interceptor);
        bindInterceptor(Matchers.any(),   Matchers.annotatedWith(Cacheable.class),
            interceptor);
    }

}

所以基本上,我想在我的 MethodInterceptor 中注入 localStore、remoteStore 和 cacheUtils,并将我自己的实现映射到我的 3 个模块中。但这没有用。我想我只是对 requestInjection() 感到困惑。在文档中,requestInjection 这样做

Upon successful creation, the Injector will inject instance fields and methods of the given object.

但是我们在哪里指定接口和实现之间的映射class?我怎样才能让我想做的事情发挥作用?

requestInjection 只会注入字段和方法——它不会调用构造函数并且对构造函数上的 @Inject 注释一无所知。如果您将 @Inject 添加到您的所有字段,您的代码应该会按预期工作。