When to use Spring prototype scope?

2019-01-22 21:30发布

问题:

I want to know when should i exactly use the prototype scope in Spring? I have understood that singleton returns the same object instance if the bean is requested for.

Then why should we consider prototype?

Explanations with examples would help a lot to understand the need for it.

回答1:

To be clear simple definitions:

  • Prototype scope = A new object is created each time it is injected/looked up. It will use new SomeBean() each time.

  • Singleton scope = The same object is returned each time it is injected/looked up. Here it will instantiate one instance of SomeBean and then return it each time.

Prototype bean is created at the time of usage. So when you would like to have statefull beans there is strong need sometimes to have prototypes scope or when you don't wont to cache any values in beans. Prototype bean can be associated with one session or some call.

Example:

A data access object (DAO) is not typically configured as a prototype, because a typical DAO does not hold any conversational state; it was just easier for this author to reuse the core of the singleton diagram.



回答2:

There are some interesting use cases by using scope prototype you will build a better and reliable application design/architecture, for example, a real-time system.

Imagine that you must build a real-time system for vehicle tracking, and you will have 2.000.000 cars sharing information every 5 seconds, In the server side, you will work with two or more distinct group of configurations, one for Cars and another one for Trucks.

Based on this simple example, if you design your application to work with distinct configuration groups in memory through the prototype pattern you will achieve a better performance.

So, in this case, whenever the server receives a new message from a Truck, for example, the server will get the instance of the configuration in memory from a hashmap of instances of VehicleGrupConfiguration and then apply the configuration behavior that this message must have, e.g: like time-out, retry... and etc.

I would like to highlight that there are many ways to implement this situation, but this example shows that a prototype pattern is very powerful in matters of performance and design patterns.