Member-only story

Spring’s Request vs Session Scope

Namrata
5 min readFeb 27, 2024

--

In Spring Framework, a bean’s scope determines the lifecycle and visibility of that bean in the contexts it is being used. There are five types of bean scopes supported :

  1. Singleton (default): This is the default scope for a Spring Bean. Only one instance of the bean will be created for each Spring IoC container. A real-world example could be a service class, like UserService or ProductService, where you may only need a single instance of the bean.
  2. Prototype: A new instance will be created every time the bean is requested. This is useful when you want a bean to hold state that is specific to the client. For example, if you have a bean that holds a shopping cart, that bean needs to be prototype scoped because every user will need to have their own shopping cart.
  3. Request: A new bean will be created for each HTTP request. This is only valid in the context of a web-aware Spring ApplicationContext. This could be useful for a bean that carries information specific to an HTTP request, such as a UserContext bean that holds user information.
  4. Session: A new bean will be created for each HTTP session by the container. This is also only valid in the context of a web-aware Spring ApplicationContext. A common use case would be user authentication. Once a user is authenticated, the same user data needs to be available for that entire session.
  5. Global Session: This is a bean scope that is scoped at the global HTTP session level. It is typically only used when creating…

--

--

Namrata
Namrata

Written by Namrata

Engineering @Microsoft A software developer writing her daily bits . https://www.linkedin.com/in/namrataagarwal5/

No responses yet