What is the Spring Bean prototype used for?

By default, the Bean created by Spring is single. They are thread safe because they are stateless. When we want Spring to create a stateful Bean, we need to use the prototype area to define the Bean. We need to take care of threading issues. All Bean statelessness will be contaminated when they are introduced by the prototype bean. So I just can't figure out where we can use the prototype area. Can you give some typical scenario that we can / should use a prototype Spring Bean? Also, how can we reverse state pollution on another beans single?

+8
spring prototype thread-safety singleton
source share
2 answers

There are many reasons to use the prototype area, for example, at any time when you use the "new" instead of using singleton code. For each bean user, for each bean request, a collection of unique beans, etc. After all, in any non-trivial application do you use non-singleton much more than single ones?

Singleton-scoped beans are not thread safe simply because they are singleton - they must be written to be thread safe. They do not become magical. A bean area is simply this: its scope: it does not make a bean suitable for a specific area - it is up to the developer.

+13
source share

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

I myself prefer the factory approach. One of the reasonable scenarios for the prototype area that I came across was a stateful object, needed for different famous beans, and each of them required its own copy. The highlighted factory class will be redundant in this scenario, since I don’t need to create objects on the fly, but only when using other beans. "

+1
source share

All Articles