How can spring singleton bean be used for apathy without talking?

Good morning. This morning when I go through the Spring reference I come across the following statement

As a rule, use the prototype scope for all stateful beans and the singleton
scope for stateless beans.

      

Context.getBean (...) will always return a newly created object if the scope bean is "prototype". Then how could we achieve the function of the state? How can I keep the conversation going here?

Likewise, the "singleton" will only be created once for each container. Thus, with multiple requests, it contains the same dataset (I mean the last state to be more precise). Then that's all about the above instruction from the Spring reference document. I was so confused. Please help me understand the statement? Maybe I'm wrong.

+3


source to share


2 answers


In our CRUD application, Spring DAO is singleton. That is, only the jdbc template initialization is a class level variable. Other logic is part of the method call. So, in fact, the state is part of the stack frame, not the heap, and is therefore thread safe.



0


source


Think of it this way:

Imagine you have a bean - eg. a service that contains the state of a complex call (and possibly calls other components used by the service) via some private fields. If two calls happen to this bean / service at the same time, the state is compromised as the member fields cannot handle the state of two concurrent calls. If you want to hold state for two simultaneous calls, you probably need to store state on some card where the key was, for example. thread identifier.



However, if you are using a prototype bean, a new bean is created for each request / call (service in the example) and the state can be safely stored in the private fields of the bean since the bean will not be used for different requests.

Note that if you want to persist state across multiple requests (e.g. session state or the like), it is possible to store the state in some kind of state store (e.g. singleton bean with a map, or better yet, a cache based, for example, on EhCache) ...

0


source







All Articles