2015-06-20 59 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' –

相关问题