How exactly works the Spring session scope of a bean? what is the default scope of a bean in the web context?
- You use spring session beans for beans which are stateful and their state differs per user. These can be for example preferences of currently logged in user.
- Default scope of bean in spring is singleton and it is no different in Web Application context.
Note than in web environment you can use also REQUEST scoped beans and their lifetime is only per one user request. You should use request scope when session is not necessary and request is sufficient.
Also, in portlet environment, you can use another scope which is GLOBAL SESSION. Each portlet has its own indepenednt session and typically those portlets are preffered to have their own state encapsulated only for themselves. But if you need to share session data among different portlets, you will need to use global session scope.
Ans 1) session scope is very similar to HttpSession scope. Beans instantiated based on session scope scope lives through the HTTP session. Similar to request scope, it is applicable only for web aware spring application contexts.
/** * Annotation-based configuration of session scope */
@Component
@Scope("session")
public class ShopCart { }
and then
@Inject
private ShopCart cart;
Ans 2) Default is Singleton everywhere.
Actually Spring help you create Session scope bean instead traditional way
httpSession.setAttribute("Object",new Object());
&&
httpSession.getAttribute("Object");
and Spring provide this efficient way
@Component
@Scope("session")
public class Foo{
}
now it's headache of spring to create and destroy this associated session object using Factory Pattern