且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

访问无状态内部有状态的现有实例,java ee 6

更新时间:2023-12-03 16:00:46

您应该永远@Stateless@Stateful bean (SFSB)/code> bean (SLSB).SFSB 的生命周期与其客户端的生命周期一样长(客户端是注入 SFSB 的实例,在本例中是 SLSB 本身).然而,SLSB 旨在成为无状态,并且大多数容器将它们放在一个池中.因此,每当 SLSB 在使用后返回池中时,它将在其他地方完全重用,但它拥有与第一次创建 SLSB 时相同的 SFSB 实例!这可能会导致不良结果.

You should never inject a @Stateful bean (SFSB) in a @Stateless bean (SLSB). A SFSB lives as long as its client lives (the client is the instance where the SFSB is been injected, which is in this case the SLSB itself). SLSB's are however intented to be stateless and most containers have them in a pool. So whenever the SLSB goes back to the pool after use, it will be reused entirely elsewhere, but it holds the same SFSB instance as it was when the SLSB was been created for the first time! This may lead to undesireable results.

此外,每次当您从 JNDI 获得 SFSB 时,您都会获得一个全新实例,这与 在其他地方共享的 SLSB 不同.SFSB 的客户端就是当前的客户端类实例,您从 JNDI 获取 SFSB.您应该自己保留这个实例并重用相同的实例,直到您完成对它的事务处理.其中一种方法是自己将其存储在 HTTP 会话中,或存储在您正在使用的 MVC 框架的会话范围托管 bean 中.

Also, everytime when you get the SFSB from JNDI, you will get a brand new instance which is unlike SLSBs not shared elsewhere. The SFSB's client is then the current client class instance where you've got the SFSB from JNDI. You're supposed to keep hold of this instance yourself and reuse the very same instance until you're finished with performing the transaction on it. One of the ways is storing it in the HTTP session yourself or in a session scoped managed bean of the MVC framework you're using.

功能需求对我来说并不完全清楚,因此很难给出如何解决您的特定问题的合适答案,但我的印象是您实际上需要将用户存储在HTTP 会话,不在 SFSB 中.对于会话 bean,初学者最常见的错误是它们将 EJB 上下文中的会话"错误地解释为 HTTP 会话.

The functional requirement is not entirely clear to me, so it's hard to give a suitable answer how to solve your particular problem, but I have the impression that you actually need to store the user in the HTTP session, not in a SFSB. The most common beginner's mistake as to session beans is namely that they incorrectly interpret the "session" in EJB context as being the HTTP session.

另见关于同类问题的相关答案以获得更深入的解释:JSF 请求范围的 bean 不断在每个请求上重新创建新的有状态会话 bean? 根据您的问题历史记录,您对 JSF 很熟悉,所以这个答案应该很容易理解.

See also this related answer on a question of the same kind for a more in-depth explanation: JSF request scoped bean keeps recreating new Stateful session beans on every request? According to your question history you're familiar with JSF, so this answer should be easy understandable.