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
这种行为?
我检查了SessionScope和RequestScope的实现,看起来他们也使用'ThreadLocal' –