简体   繁体   English

无状态与有状态的豆子

[英]Stateless vs stateful beans

I still don't understand clearly the difference of stateless and stateful beans in EJB. 我仍然不清楚EJB中无状态和有状态bean的区别。 In which situation should I use stateless and in which stateful? 在哪种情况下我应该使用无状态和有状态的?

I will give you good example: 我会举个很好的例子:

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. 用户(比如客户)现在有一个bean只是将国家名称作为输入并提供该国家的货币。 In this case a bean can be used for n no. 在这种情况下,bean可用于n no。 of users (clients). 用户(客户)。 It does not make any sense creating individual bean for each client request. 为每个客户端请求创建单独的bean没有任何意义。 So there could be such a bean which can be served to multiple clients and such bean is known as stateless bean. 所以可能有这样一个bean可以提供给多个客户端,这种bean被称为无状态bean。 After a stateless bean served a client, it does not destroy but goes to bean pool, so it can serve to other clients. 在无状态bean服务于客户端之后,它不会销毁但是会转到bean池,因此它可以服务于其他客户端。

Now let's take an another example, 现在让我们再看一个例子,

In a shopping cart, there is a bean which can contain list of items. 在购物车中,有一个可以包含项目列表的bean。 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. 因此,当您在网上购物时添加商品时,这些商品将保存在一个专门为您创建的bean中。 Its life time will be till you finish the shopping. 它的生命周期将一直到你完成购物。 So if I start shopping online, for me another bean will be created. 因此,如果我开始在线购物,对我来说将创建另一个bean。 So the reason it is said stateful because it's state remains active though out the whole session ie from you start adding the first item till you add n no. 因此它被称为有状态的原因是因为它的状态在整个会话期间保持活动状态,即从你开始添加第一项直到你添加n否。 of items into the cart and place the final order. 将物品放入购物车并下订单。

Stateless bean: A bean can serve to multiple clients (any changes by one client would be reflected to other client). 无状态bean: bean可以服务于多个客户端(一个客户端的任何更改都会反映到其他客户端)。 Once a stateless bean is no use, it doesn't destroy, rather it goes to bean pool, so in future it can serve to other clients. 一旦无状态bean没有用,它就不会破坏,而是进入bean池,因此将来它可以服务于其他客户端。

Stateful Bean: One bean only for one client. 有状态Bean:仅一个客户端的一个bean。 (Any changes by one client will be only for that client as there is no use of this bean for other clients). (一个客户端的任何更改都只适用于该客户端,因为其他客户端不使用此bean)。 So once it's service is over, it's getting destroyed. 所以一旦它的服务结束,它就会被破坏。

If you need to maintain a state of the client between the invocations you should use guess what? 如果您需要在调用之间维护客户端的状态,您应该使用猜测什么? Right, stateful beans. 对,有状态的豆子。 If you do not care about the state - stateless bean is the right choice. 如果你不关心状态 - 无状态豆是正确的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM