Question
A. Yes, one per request
B. Yes, it’s a singleton
C. No, it’s prototype scoped
D. Depends on the HTTP method
Answer
B. Yes, it's a singleton
Spring Controller Lifecycle
Spring controllers annotated with @RestController
(or @Controller
) are singleton beans by default. This means:
One instance of the controller is created per application context
All requests are handled by the same controller instance
Multiple threads can access the same controller instance simultaneously
Thread Safety Implications
Since controllers are singletons, we must be careful about shared mutable state:
Best Practices for Thread-Safe Controllers
1. Avoid Instance Variables for Request Data
2. Use Dependency Injection Safely
3. If You Need Mutable State, Use Thread-Safe Options.
When Controllers Aren't Singletons
We can change the scope, but it's rarely needed:
Conclusion
Controllers are singletons by default
Multiple requests = multiple threads accessing the same controller instance
Never store request-specific data in instance variables
Stick to stateless controllers with injected dependencies
Use method parameters and local variables for request data