Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the prototype Spring Bean used for?

By default, the Bean created by Spring is singleton. They are thread-safe because they are stateless. When we want Spring to create a stateful Bean, we need to use prototype scope for the Bean definition. We need to take care of the thread-safe issues for them. All stateless Bean will be polluted when they are injected by the prototype bean. So, I just can not image where we can use the prototype scope. Can you give some typical scenario that we can / need to use prototype Spring Bean? Also how can we void the stateful pollution on other singleton beans?

like image 658
Jacky Avatar asked May 13 '12 09:05

Jacky


People also ask

What is a prototype bean?

Basically a bean has scopes which defines their existence on the application. Singleton: means single bean definition to a single object instance per Spring IOC container. Prototype: means a single bean definition to any number of object instances.

What is prototype in Spring?

Prototype scope in the spring framework creates a new instance of a bean, every time; a request for that specific bean is made. The Prototype scope is preferred for the stateful beans, and the spring container does not manage the complete lifecycle of a prototype bean i.e. destruction lifecycle methods are uncalled.

Can we use prototype bean in singleton bean?

You cannot dependency-inject a prototype-scoped bean into your singleton bean, because that injection occurs only once, when the Spring container is instantiating the singleton bean and resolving and injecting its dependencies.


2 Answers

There are many reasons to use prototype scope, e.g., any time you'd use "new" instead of using a singleton. A per-user bean, a per-request bean, a collection of unique beans, etc. After all, in any non-trivial application, don't you use non-singletons far more than singletons?

Singleton-scoped beans aren't thread-safe simply because they're singletons–they must be written to be thread-safe. They don't become thread-safe magically. A bean's scope is just that, its scope: it doesn't make the bean appropriate for the particular scope–that's up to the developer.

like image 72
Dave Newton Avatar answered Sep 20 '22 15:09

Dave Newton


I perceive prototype scoped beans as an alternative to factory classes used to create objects. The difference is in case of prototype beans spring will save you some code for dependency injection and will also automatically proxy your objects for transactions etc. when appropriate.

I myself prefer the factory approach. One reasonable scenario for prototype scope I encountered was a stateful object, needed by different known beans and each required its own copy. A dedicated factory class would be redundant in this scenario since I did not need to create objects on the fly but only during other beans' instantiation.

like image 25
mrembisz Avatar answered Sep 20 '22 15:09

mrembisz