In case of REST implementations in Spring, spring Controllers are singleton. I want to know why spring controllers are singleton apart from thread-safety issue. Please help in resolving this issue.
Asked
Active
Viewed 1.5k times
11
-
1Rest implementations should be stateless, so there is no need for a statefull bean. – Ralph Dec 24 '13 at 07:51
-
@Ralph what if we autowire an HttpSession? Shouldn't the controller be instantiated again? – Hola Soy Edu Feliz Navidad Sep 10 '19 at 15:53
-
@Hola Soy Edu Feliz Navidad: REST is intended to been stateless: so if you need an http session in your controller, than it is likely that you do not have an REST API – Ralph Sep 15 '19 at 07:32
-
@Ralph So, how would you check who is the current user? Decoding the token? – Hola Soy Edu Feliz Navidad Sep 15 '19 at 18:38
-
@Hola Soy Edu Feliz Navidad: move discussion to https://chat.stackoverflow.com/rooms/199578 – Ralph Sep 17 '19 at 14:07
1 Answers
14
This has nothing to do with REST.
Spring beans are, by default, singleton scoped. Since component scanning a @Controller
annotated class simply generates a bean, that bean will be singleton scoped.
For reasons why a @Controller
bean should be stateless, read any and all of the following:
To follow up on the REST question, REST is meant to be stateless. In other words, each request contains all the information it needs for the server to handle it. Knowing that, it's pointless for the server (or @Controller)
to keep any information after it's finished handling the request in instance fields and the like. Therefore a singleton is the way to go.

Community
- 1
- 1

Sotirios Delimanolis
- 274,122
- 60
- 696
- 724