有没有办法让Guice绑定到新请求时创建的某种类型的实例?
使用ThreadLocal
的伪代码:
// 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
的情况下实现此行为吗?
答案 0 :(得分:1)
Guice有Scopes的概念。听起来你正在寻找与@RequestScoped
注释绑定的东西。这将绑定一个在请求生命周期中持续存在的实例,并为下一个请求注入一个新对象。
当您希望对象在整个会话中持续存在时,还有@SessionScoped
。
You can read up on their examples here,其中包含some language on how to use @RequestScoped
。