Basic Guide To Spring Bean Scope And Implementation In Spring
Posted By : Ankur Bansala | 30-Jul-2018
Bean Scope:
When you define a bean you also can define the scope of the bean, and by defining scope what you actually do is take control of how many instances
(s) will be created of a particular bean on total requests for the bean. Spring framework has total five type of scope available for
a bean and in a bean definition, we can use one of them. Default bean scope is Singleton.
Singleton:
While using singleton scope Spring IOC container only creates one instance for that bean definition and it is cached in memory.
The further request for the bean gets the same instance reference created first by IOC container. Default scope of every bean is the singleton.
Following diagram illustrates about singleton scope.
Prototype:
If you define bean scope as the prototype then IOC container will create the new instance on every single request of that bean.
Following diagram illustrates about prototype scope.
Request:
Request scope is only used while developing web apps. Using the request scope one instance of the bean is created by the IOC container for
every HTTP web request. When a request finished processing bean associated with that request will be destroyed.
By using bean configuration like one below, IOC container will create an instance scoped to each and every object.
@Component
@Scope(“request”)
Class RequestScopeExample {
}
Session:
Using session scope Spring IOC container will create a new instance of defined bean for the lifetime of one session.
That is only one instance of a specified bean will be created for one user between his/her multiple requests.
Session scope is also used only with web apps.
Following is an example of session scope.
@Component
@Scope(“session”)
Class SessionScopeExample {
}
GlobalSession:
We use Global Session scope in the application and also with the portlet container, now notice that each portlet container having
it's own session.
Portlets are part of the JSR-168 standard that modulates portal containers and components.
If we talk about the difference between portlet vs servlet could be that while servlet always responds to the single action
eg: request and portlets (due to nature) have to respond to two type of action eg: render and request.
@Component
@Scope(“globalsession”)
Class SessionScopeExample {
}
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Ankur Bansala
Ankur is an experienced Java back-end Developer and having capabilities to build web application.