Spring bean scopes
Bean scopes define the lifecycle and visibility of a bean within a Spring container
Singleton
A single instance of the bean is created for the entire Spring container
It is the default scope if not specified
The Spring container manages the creation and destruction of the singleton bean
Singleton-scoped beans are shared across all HTTP requests, and their lifecycle is managed by the Spring container
It's crucial to ensure thread safety in singleton beans and be mindful of the shared state when designing components that are used across multiple requests
  @Component
  public class MySingletonBean {
      // Bean definition
  }
  
Prototype Scope
A new instance of the bean is created every time it is requested, and the Spring container does not manage the destruction of prototype-scoped beans
It is the responsibility of the client code to release resources and manage the lifecycle
It is often used for stateless or stateful beans that require a short lifecycle and should not be shared between different parts of the application
  @Component
  @Scope("prototype")
  public class MyPrototypeBean {
      // Bean definition
  }
  
  
Request Scope
A new instance of the bean is created for each HTTP request, and the instance is destroyed when the request is completed
Suitable when you need to maintain stateful information during the processing of a single HTTP request. Each user request gets its own instance of the bean. Doesnot share state.
The Spring container manages the creation and destruction of request-scoped beans, making it suitable for scenarios where resource cleanup is necessary at the end of each request
Typically, request-scoped beans are not shared between threads, ensuring a level of thread safety within the context of a single HTTP request
  @Component
  @Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
  public class MyRequestScopedBean {
      // Bean definition
  }
  
Session Scope
A new instance of the bean is created for each HTTP session
The instance persists and remains active throughout the duration of the user's session
Suitable for maintaining stateful information across multiple requests within the same user session
The Spring container manages the creation and destruction of session-scoped beans
Resources associated with the bean are released when the user session ends or times out
Session-scoped beans are not inherently thread-safe. If multiple threads simultaneously access the same user session, they might access the same instance, leading to potential thread safety issues
  @Component
  @Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
  public class MySessionScopedBean {
      // Bean definition
  }