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' –