Guice注入每次请求时创建的上下文实例

时间:2015-06-20 10:25:03

标签: java dependency-injection request guice

有没有办法让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的情况下实现此行为吗?

1 个答案:

答案 0 :(得分:1)

Guice有Scopes的概念。听起来你正在寻找与@RequestScoped注释绑定的东西。这将绑定一个在请求生命周期中持续存在的实例,并为下一个请求注入一个新对象。

当您希望对象在整个会话中持续存在时,还有@SessionScoped

You can read up on their examples here,其中包含some language on how to use @RequestScoped