确切地说,@Inject 注释何时在 Servlet 中启动 SessionScoped bean 的注入?
我需要修改 Servlet 中的用户会话对象(SessionScoped bean - CDI),因此我必须以某种方式获取该 bean。我按以下方式使用注入:
@Inject
private UserSession user;
其中 UserSession 是 SessionScoped CDI bean。 user 方法是从 doPost 或 doGet servlet 方法调用的。 这很完美;每次 @Inject 注释都会注入适当的 UserSession bean,但我不明白如何实现此行为。
我假设用 @Inject 注释的 bean 仅注入一次(当创建对象(本例中为 Servlet 实例)时),但这显然是一个错误的假设。
那么,这些bean什么时候注入到servlet中呢?按要求?当存在多个 UserSession 对象时,这种方法如何避免冲突(一个 servlet 实例 - 多个线程来处理它)?
I need to modify a user session object (SessionScoped bean - CDI) in a Servlet, so I have to obtain that bean somehow. I used injection in the following way:
@Inject
private UserSession user;
where UserSession is the SessionScoped CDI bean. user methods are called from either doPost or doGet servlet methods.
This works perfectly; every time the @Inject annotation injects the appropriate UserSession bean, but I don't understand how this behavior is achieved.
I assumed that the beans, annotated with @Inject, are injected only once (when the object - Servlet instance in this case - is created), but it is obviously a wrong presumption.
So, when are these beans injected into the servlet? Per request? And how does this approach avoids conflicts (one servlet instance - multiple threads to deal with it) when there are multiple UserSession objects?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
CDI 使用代理模式。注入的实例实际上不是真实实例,而是一个代理,它根据当前上下文定位真实实例并将所有方法委托给它(就像 EJB 的工作方式一样)。
UserSession
bean 的自动生成类大致如下所示:此机制允许您将较窄范围的实例注入较宽范围的实例中,并允许您仍然在当前上下文中获取预期的实例。标准 JSF
@ManagedProperty
注释不支持它,只是因为它不使用代理,而是直接注入所需的实例。这就是为什么不可能通过@ManagedProperty
注入更窄范围的东西。另请参阅:
The CDI uses the proxy pattern. The injected instance is actually not the real instance, but a proxy which locates the real instance depending on the current context and delegates all methods to it (like as how EJBs work). The autogenerated class of your
UserSession
bean looks roughly like this:This mechanism allows you to inject instances of a narrower scope in instances of a broader scope and allows you to still get the expected instance in the current context. The standard JSF
@ManagedProperty
annotation doesn't support it, simply because it does not use a proxy, but injects the desired instance directly. That's why it's not possible to inject something of a narrower scope by@ManagedProperty
.See also:
你的答案就在CDI的C中,它代表Contexts。
所发生的情况是,注入的不是实际的 bean,而是代理。该代理是上下文相关的,并根据代表执行代理的调用者的上下文解析为实际的会话作用域 bean。
Your answer lies in the C of CDI, which stands for Contexts.
What happens is that not the actual bean is injected, but a proxy. This proxy is contextual and resolves to the actual session scoped bean depending on the context of the caller on who's behalf the proxy is executed.