2

Is it to ensure that the controllers are thread safe?

If the above case is true, then is it necessary to go through the overhead of bean creation for each request rather than making the controller code not rely on instance variables?

Satadru Biswas
  • 1,555
  • 2
  • 13
  • 23

2 Answers2

5

Your default position should be to use singleton controllers which are thread-safe. This partly for performance reasons, as you say, and partly for reasons of good design - a large mass of stateful, request-scoped beans is a mess.

Using request-scoped controllers (or other request-scoped beans) is a specialised requirement which you should only use when you have good reason to do so, i.e. you have beans whose state must be private to the lifecycle of that particular request.

skaffman
  • 398,947
  • 96
  • 818
  • 769
  • hi @skaffman , can you please clarify my questions - https://stackoverflow.com/questions/70993679/standard-scope-for-spring-classes/70995719?noredirect=1#comment125505833_70995719 thanks – Shweta Priyadarshani Feb 05 '22 at 14:53
  • and this one too - https://stackoverflow.com/questions/70993624/will-a-new-instance-of-singleton-scoped-object-in-a-webapplicationcontext-be-cre – Shweta Priyadarshani Feb 05 '22 at 14:53
2

Request scoped beans are short living instances of a class, they will be created when a new request comes in.

Singleton beans live the entire lifetime of your application. Note: If you have a multi user application with several sessions, all users will access the same instance of your beans, if they are singletons.

I would prefer Request scoped beans whenever possible in a web application.

flash
  • 6,730
  • 7
  • 46
  • 70
  • Why would you prefer stateful application over stateless application? Spring IOC is intended to keep things stateless (as much as possible). I feel like you did not understand the question and answered it with your own opinion. Mind editing it? – nabster Oct 14 '19 at 13:56
  • JAX-RS (Jersey) is default request scope. Perhaps Spring and JX-RS handle controller instantiation in a different way, but I tend to think its similar. A web request should be a very quick operation and the controller should not be huge. Having worked in J2ee quite a bit, I much prefer the code structure of Request Scoped; i.e. I don't have to pass args around everywhere to each method and I get the added benefit of thread safety. If everything is always a singleton, why not just make everything static? Just creating one and letting GC do its job seems like a valid approach also. – Hodglem Jan 06 '20 at 16:50
  • "If everything is always a singleton, why not just make everything static?" It would make a hell of unit testing. And in Spring there is no need of passing around arguments. You may access to request everywhere as request is bounded to the current thread. Although I prefer to access request only from web tier. – Rober2D2 Oct 20 '20 at 18:40