This article presents the different scopes on Spring managed beans. This is one of the greatest advantage using spring's managed beans. Every bean definition can be declared with different scopes. If you are the beginner learning the Spring Framework first time, please read our introduction articles on the Spring Framework :
* Introduction to Spring Framework
* Introduction to Spring Framework AOP
* List of Spring Articles
Lets look into the different types of bean scopes in the coming sections.
Types of Scopes
The five different types of scopes supported in the Spring Framework are as follows :
* Singleton
* Prototype
* Request
* Session
* Global Session
The following sections explains each type of scope in detail with syntax.
Singleton Scope
Singleton is the default scope for all the beans defined in the Spring's configuration files. If a specified bean is declared as singleton, spring container will create only one instnce of the bean. All the requests coming to that bean will be served by the same instance and there won't any other instances created for the same bean. The created bean instance is stored in the cache and used for the all the incoming requests for the same bean.
Singleton design pattern concept and the way spring handles singleton beans are different in the approach where the normal Singleton class. Singleton class creaets only one instance per the classloader, spring creates one instance for each spring container. For example, if there is multiple spring container are running inside a single classloader, the singleton beans are specific to that container which they are created.
Look into the sample code how to declare a singleton bean:
All the three definitions are the same. As we mentioned earlier, if you don't specify any scope for the bean definitions, container will assign singleton scope.
Prototype Scope
Prototype Scope is non-singleton scope where new instance will be created for every request. This type of beans are more suitable for creating stateful beans where singleton beans used for creating the stateless beans.
When you are using the Prototype Scope, application developer's responsibility to handle the many of the call back methods where in the singleton beans it is handled by the container. Specifically, application developer has to handle all the destruction callbacks programatically, because container just hand over the beans to the application once created successfuly. After that container doesn't have any control on the prototype beans.
Build Your Own Test Framework
-
[image: Build Your Own Test Framework]
Learn to write better automated tests that will dramatically increase your
productivity and have fun while doing so...
2 hours ago
No comments:
Post a Comment
I'm certainly not an expert, but I'll try my hardest to explain what I do know and research what I don't know.