java - 如何在 servlet 线程中获取新的有状态 session bean?

标签 java servlets dependency-injection jakarta-ee ejb-3.0

我正在试验 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 的更多信息,您可能对我的这些其他回答感兴趣:

希望对您有所帮助。

关于java - 如何在 servlet 线程中获取新的有状态 session bean?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2833457/

相关文章:

Java排序列表

java - 尝试使用 Java (JMS) 中的选择器在 Tibco EMS 上使用持久消息时遇到问题

java - 究竟什么是集成测试 - 与单元相比

java - 小服务程序测试

在 web.xml 中添加 servlet 后 tomcat 404 not found 错误

java - 尝试注入(inject)两个具有通用实现的存储库失败

java - 与 ribbon/eureka 一起使用时假装客户端错误

eclipse - 使用 Macbook PRO 在服务器 tomcat 上运行 servlet 时出现 404 错误

java - SpringSecurity RememberMeServices 不是通过注解注入(inject)的

angularjs - 使用 RequireJS 延迟加载 AngularJS DI 组件