Reputation: 198
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
Upvotes: 8
Views: 3606
Reputation: 2422
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.
Spring handles this by implementing IoC container which is described here.
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.
No, unless you specify your beans as non-singleton scoped.
Spring has decent documentation both for Core and Web modules. You can find it here:
Upvotes: 11