Here we will see different scope on spring managed beans.There are five types of scope which will support by spring
- singleton
- prototype
- request
- session
- global session
Now lets look into each of these sessions in detail.
singleton scope:
This is default scope for all the beans defined in the spring configuration. If you specify a bean’s scope as singleton , Spring will create only one instance and will share with all the subsequent request for this instance.There will be only one instance for a particular bean if we declare it as singleton.Once a bean instance created it is stored in the cache and used for the all the incoming requests for the same bean.
Declaration:
1 |
<bean id="sampleClass" class="com.j2eereference.SampleClass" scope="singleton"/> |
With the above bean definition the Spring container will create a brand new instance of SampleClass bean only for the one time .
prototype scope:
In this scope, container will create a new instance for every request.
Declaration :
1 |
<bean id="sampleClass" class="com.j2eereference.SampleClass" scope="prototype"/> |
With the above bean definition the Spring container will create a brand new instance of the SampleClass bean for each and every new request.
request scope:
This scope use only in web-based applications.
This is similar as HttpServletRequest.When new request comes in, the new instance will be created. Request Scope beans are created for every request.Here the object’s lifetime ends when the request is completed.
Declaration :
1 |
<bean id="sampleClass" class="com.j2eereference.SampleClass" scope="request"/> |
With the above bean definition the Spring container will create a brand new instance of the SampleClass bean for each and every HTTP request.
session Scope:
This scope use only in web-based applications.
It is similar to the HttpSession . Here beans are created and stored for each session. When new request comes in, the new instance will be created and the object’s lifetime ends when the session is closed.
Declaration :
1 |
<bean id="sampleClass" class="com.j2eereference.SampleClass" scope="session"/> |
With the above bean definition the Spring container will create a brand new instance of the SampleClass bean for each and every new session.
global session scope :
This scope use only in web-based applications.
The global session scope is similar to the Session scope and really only makes sense in the context of portlet-based web applications. The portlet specification defines a global Session that is shared by all of the various portlets that make up a single portlet web application. Beans defined at the global session scope are available till the global portlet Session is active.
Declaration :
1 |
<bean id="sampleClass" class="com.j2eereference.SampleClass" scope="globalSession"/> |
With the above bean definition the Spring container will create a brand new instance of the SampleClass bean for each and every new global session.
Leave a Reply