Spring singleton bean

I know this question may seem naive, but I have confusion regarding the bean scope in the web application. I know that for each request a new stream is generated by the container in the same way in the case of the spring web application, a new stream is created for each request, why it is proposed to define my controller, the service as singleton, the volume of these beans should not be a prototype, because each request , i.e. the stream will have its own instance of the controller, a service to work with.

Please enlighten me.

+5
source share
4 answers

https://gottalovedev.wordpress.com/2014/11/23/bean-scope/

Let it read. I am sure this will help.

+1
source

This will be a huge amount of overhead. There is no reason why each request needs its own bean service if you make the code valid in streaming mode, which usually means not storing any request state in the bean.

+6
source

Even if a new thread is created (or reused depending on the configuration), the controller and service instances are reused. If the controllers and services are well designed, they can be unstable in relation to the request and invariable, which will make them thread safe. It would also lead to much less creation of objects when their state does not change after they are created.

+3
source

I think it really depends on whether you need to store any state in the bean. Usually I write my singleton so that they do not contain any state and are used only to calculate business logic. Without the state to be managed, it is then acceptable that all threads share the same oneton instance.

0
source

Source: https://habr.com/ru/post/1208954/


All Articles