gpt4 book ai didi

java - Guice 注入(inject)根据每个请求创建的上下文实例

转载 作者:行者123 更新时间:2023-11-30 08:07:02 25 4
gpt4 key购买 nike

有没有办法拥有 Guice绑定(bind)到根据新请求创建的某种类型的实例?

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 的情况下实现此行为吗?

最佳答案

Guice 的概念是 Scopes 。听起来您正在寻找与 @RequestScoped 绑定(bind)的东西注解。这将绑定(bind)一个在请求生命周期内持续存在的实例,并为下一个请求注入(inject)一个新对象。

还有@SessionScoped当您希望对象在整个 session 中持续存在时。

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

关于java - Guice 注入(inject)根据每个请求创建的上下文实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30952908/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com