When we deploy a Spring web application. How the webserver handles multiple user's requests for the same bean defined in Spring? In case of singleton beans does only one bean is created for multiple users requests? How the single WAR file is used by multiple user's requests?
1 Answers
i refereed from some stack over flow previous questions .. :)
Singleton bean in Spring and Singleton pattern is quite different. Singleton pattern says that one and only one instance of a particular class will ever be created per classloader.
THe scope of Spring singleton is described as per container per bean. It is the scope of bean definition to a single object instance per Spring IoC container. The default scope in Spring in Singleton.
Eventhough the default scope is singleton, you can change the scope of bean by specifying the scope attribute of element.
Every web request generate a new thread as explained in this thread.
Spring manages different scopes (prototype, request, session, singleton). If two simultanous requests access a singleton bean, than the bean must be stateless(or at least synchronized to avoid problems). If you access a bean in scope request, then a new instance will be generate per request. Spring manages this for you but you have to be careful and use the correct scope for your beans. Typically, your controller is a singleton but the AppModel has to be of scope request otherwise you will have problems with two simultanous requests. This thread could also help you.
About your last question "how this magic is happening?", the answer is "aspect/proxy". Spring create proxy classes. You can imagine that Spring will create a proxy to your AppModel class. As soon as you try to access it in the controller, Spring forwards the method call to the right instance.