我正在试验 EJB3
我想将一个有状态 session bean 注入(inject)到一个 servlet 中,这样每个访问该 servlet 的用户都会获得一个新的 bean。
显然,我不能让 bean 成为 servlet 的实例变量,因为它将被共享。显然不允许注入(inject)局部变量。
我可以使用 new 运算符创建一个 bean,但这似乎不是正确的方法。
有没有正确的方法来做到这一点?看起来我想要做的事情相当简单,毕竟我们希望每个新客户都能找到一个空的购物车。
最佳答案
您不能使用 new
来获得新的 SFSB。
您通常做的是使用InitialContext
查找
一个新的。
MyBean bean = (MyBean) new InitialContext().lookup( name );
然后您将获得对特定 SFSB 的引用,您可以跨请求重复使用该引用。
来自 this answer :
You should not typically inject SFSB, unless it is into another SFSB or into a Java EE client. You should use @EJB on the referencing class (e.g. your servlet) to declare the ejb-ref and then do a JNDI lookup in the code to obtain the instance. This instance could then be placed directly in your Http session.
有关 SFSB 的更多信息,您可能对我的这些其他回答感兴趣:
- Stateful EJBs in web application?
- Java: Tracking a user login session - Session EJBs vs HTTPSession
- Correct usage of Stateful Beans with Servlets
希望对您有所帮助。
关于java - 如何在 servlet 线程中获取新的有状态 session bean?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2833457/