Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Spring controllers are singleton for REST implementations?

Tags:

spring

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.

like image 468
Sambit Avatar asked Dec 24 '13 07:12

Sambit


1 Answers

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:

  • Are Spring MVC Controllers Singletons?
  • Controller's life-cycle in Spring MVC

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.

like image 76
Sotirios Delimanolis Avatar answered Oct 11 '22 11:10

Sotirios Delimanolis