Spring Bean Scopes –
Spring Framework supports exactly five scopes (of which three are available only if you are using a web-aware ApplicationContext). singleton scope is the default scope.
Scopes a single bean definition to a single object instance per Spring IoC container. If you define a bean as singleton, only one instance will be shared among multiple request. Same bean instance being returned by the Spring container. Spring IoC container will create exactly one instance of the object defined by that bean definition. This single instance will be stored in a cache and all subsequent requests and references for that named bean will result in the cached object being returned.
<bean id=”userServiceDao” scope=”singleton”/>
Scopes a single bean definition to any number of object instances. Every time a new bean instance created when a request for that specific bean is made.
<bean id=”accountService” scope=”prototype”/>
Remaining scope request, session, and global session are for use only in web-based applications. To use these scopes you have to do initial configuration, like if you are accessing scoped beans within Spring Web MVC, then already you did configuration for DispatcherServlet and it will take care everything. If you are using JSF or Struts, you need to add the following javax.servlet.ServletRequestListener to the declarations in your web applications web.xml file.
Scopes a single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP request will have its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.
<bean id=”loginAction” scope=”request”/>
Scopes a single bean definition to the lifecycle of a HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
<bean id=”userCart” scope=”session”/>
Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.
<bean id=”appPreferences” scope=”globalSession”/>
Setting Bean scope using annotations –
public class UserCart
// code block
Latest posts by Gopal Das (see all)
- Salesforce Certified Platform Developer I – Winter ’18 Release Exam - November 23, 2017
- Salesforce Certified Platform App Builder – Winter ’18 Release Exam - November 22, 2017
- Salesforce Certified Administrator – Winter’ 18 Release Exam - November 21, 2017