I am studying Spring MVC and I have the following doubts:
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?
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?
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.
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, ...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With