java - 无状态 vs 有状态 bean

标签 java ejb

我还是没搞清楚EJB中无状态bean和有状态bean的区别。在什么情况下应该使用无状态,在什么情况下应该使用有状态?

最佳答案

我会给你一个很好的例子:

Say there are n no. of users (say clients) Now there is a bean which just takes the country name as input and provides the currency of that country. In this case a bean can be used for n no. of users (clients). It does not make any sense creating individual bean for each client request. So there could be such a bean which can be served to multiple clients and such bean is known as stateless bean. After a stateless bean served a client, it does not destroy but goes to bean pool, so it can serve to other clients.

再举个例子

In a shopping cart, there is a bean which can contain list of items. So say when you are adding the items while online shopping, the items will be maintained in a single bean which is exclusively created for you. Its life time will be till you finish the shopping. So if I start shopping online, for me another bean will be created. So the reason it is said stateful because it's state remains active though out the whole session i.e. from you start adding the first item till you add n no. of items into the cart and place the final order.

无状态 bean: 一个 bean 可以服务于多个客户端(一个客户端的任何更改都会反射(reflect)到另一个客户端)。一旦无状态 bean 没有用,它不会销毁,而是进入 bean 池,因此将来它可以服务于其他客户端。

有状态 Bean: 一个 bean 仅适用于一个客户。 (一个客户所做的任何更改将仅针对该客户,因为其他客户没有使用此 bean)。因此,一旦它的服务结束,它就会被销毁。

关于java - 无状态 vs 有状态 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11323647/

相关文章:

java - 与 EJB 的远程连接在本地主机上工作,但在 127.0.0.1 和另一台服务器上失败

java - 注入(inject)的父类(super class) Bean 如何注入(inject)错误的实例(子类 Bean 实例)?

java - EJB事务不回滚

singleton - 如何将 JBoss Singleton 服务从 JBoss AS 6 迁移到 JBoss AS 7?

java - 在android工作室:how I can create two tables with references?

java - 常量声明中的 P

java - 如何在 JButton ImageIcon 中使颜色不可见(透明)

java - 使用 AES 传输大文件

java JTree取消选择一个已经被选中的节点

unit-testing - 如何使用 JUnit5 测试 OpenEJB 中的 EJB Bean?