Issue
While developing spring-boot REST API or spring-mvc REST API, we have classes annotated with @Controller, @Service and @Repository. These all work behind a tomcat application server.
So when multiple requests arrive concurrently into the application server, is it that a new instance of controller , service and repository created for each request? How spring handles it? Does the wiring of beans occur at runtime?
Does DispatcherServlet create new instances and do their wirings for each request in new thread?
Where can I find technical details and documentation for these things.
Thanks in advance for your inputs
Solution
So when multiple requests arrive concurrently into the application server, is it that a new instance of controller, service and repository created for each request?
The answer is no. By default, all Spring beans defined with @Controller
, @Service
, @Repository
, @Component
, @Bean
or any other bean definition style are eager singletons and spring creates only one instance on application startup.
You can learn more about bean scopes on Spring's documentation.
Every request arrives in a separate thread, so you need to make them thread-safe when you're implementing your singleton beans.
How spring handles it?
Spring handles this by implementing IoC container which is described here.
Does the wiring of beans occur at runtime?
Beans wiring occur at application context startup unless you make your beans lazy if so, beans will be initiated at the first request to a bean.
Does DispatcherServlet create new instances and do their wirings for each request in new thread?
No, unless you specify your beans as non-singleton scoped.
Where can I find technical details and documentation for these things?
Spring has decent documentation both for Core and Web modules. You can find it here:
Answered By - geobreze
Answer Checked By - Cary Denson (JavaFixing Admin)