2015-06-20 78 views
1

有沒有辦法讓Guice綁定到在新請求時創建的某種類型的實例?與ThreadLocal使用Guice根據每個請求創建注入上下文實例

僞代碼:

// upon request incoming, creating the context 
Context context = new Context(request, response); 
// save to threadlocal so later on we can get it from 
// a provider 
Context.setThreadLocal(context); 
... 

// in the AppModule.java file 
modules.add(new AbstractModule() { 
    @Override 
    protected void configure() { 
     bind(Context.class).toProvider(new Provider<Context>() { 
      @Override public Context get() {return Context.getThreadLocal();} 
     }); 
    } 
}); 
... 

// in another source file 
Injector injector = Guice.createInjector(modules); 
// suppose Foo has a context property and injector shall 
// inject the current context to foo instance 
Foo foo = injector.getInstance(Foo.class); 

我可以實現無ThreadLocal這種行爲?

回答

1

Guice的概念是Scopes。這聽起來像你正在尋找與@RequestScoped註釋綁定的東西。這將綁定一個在請求生命期內持續存在的實例,併爲下一個請求注入一個新對象。

也有@SessionScoped當你希望對象持續整個會話。其中包括some language on how to use @RequestScoped

+0

我檢查了SessionScope和RequestScope的實現,看起來他們也使用'ThreadLocal' –

相關問題