【问题标题】:Injecting method interceptors in Guice在 Guice 中注入方法拦截器
【发布时间】:2015-10-10 05:50:24
【问题描述】:

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

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 个类扩展 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 会这样做

在成功创建后,Injector 将注入给定对象的实例字段和方法。

但是我们在哪里指定接口和实现类之间的映射呢?我怎样才能得到我想做的工作?

【问题讨论】:

    标签: java guice


    【解决方案1】:

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

    【讨论】:

    • 那么它可以与 setter 一起使用吗?刚刚检查过,它适用于二传手!谢谢@condit
    猜你喜欢
    • 2012-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多