2015-07-20 126 views
1

我在网上搜索过它和所有人(包括谷歌建议使用requestInjection(),但我仍然不明白如何使用它。我有一个实现方法拦截一类:Guice中的注入方法拦截器

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; 
    } 
} 

而且我有一个扩展AbstractModule 3班。

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

} 

所以我做了以下,我想注入localStore,remoteStore,在我的MethodInterceptor与我自己的实现cacheUtils在我的3个模块映射出。但是这不起作用。我想我只是与requestInjection()混淆。在文档中,requestInjection是这样的

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

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

回答

1

requestInjection只会注入字段和方法 - 它不会调用构造函数,也不会在构造函数中知道关于@Inject注解的任何信息。如果您将@Inject添加到您的所有字段,您的代码应该按照您的预期工作。

+0

那么它会与setter一起工作吗?只是检查它,它适用于二传手!谢谢@condit –