Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How exactly works the Spring session scope of a bean? what is the default scope of a bean in the web context?

Tags:

I am studying Spring MVC and I have the following doubts:

  1. What exactly is the purpose of the session scope?

Reading the documentation I know that this scopes a bean definition to an HTTP session. Only valid in the context of a web-aware Spring ApplicationContext. And also that a new instance is created once per user session.

But when exactly is it used? and for what purpose? Can you make a practical example?

  1. In Spring MVC what is the default scope in the web context?

I know that in Spring the default scope for a bean is singleton but what about the scope of a bean in the web context?

like image 343
AndreaNobili Avatar asked Apr 02 '15 12:04

AndreaNobili


People also ask

What is the default scope of a Spring bean?

Spring's default scope is singleton. It's just that your idea of what it means to be a singleton doesn't match how Spring defines singletons. If you tell Spring to make two separate beans with different ids and the same class, then you get two separate beans, each with singleton scope.

How does a Spring session scope work?

In one of my JSP based Spring MVC web apps, we use it to store data that doesn't vary after user's first request in the session i.e. we populate fields of this bean when user first comes to server & then we use ( aka read ) these values in subsequent requests ( next requests in session ) e.g. user name, user org group, ...


1 Answers

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.

like image 198
sachin k Avatar answered Oct 27 '22 07:10

sachin k