Sobes.tech
Junior — Middle

Can you explain the different levels of component scope in Spring and their meanings?

sobes.tech AI

Answer from AI

In Spring, there are several scope levels for components that determine the lifespan and visibility of beans:

  • singleton (default): one instance of the bean is created for the entire application context. All requests receive the same object.
  • prototype: a new instance of the bean is created for each request.
  • request: the bean lives for the duration of a single HTTP request (relevant for web applications).
  • session: the bean lives for the duration of a user's HTTP session.
  • application: the bean lives within the ServletContext, i.e., for the entire application.
  • websocket: the bean lives for the duration of a WebSocket session.

The choice of scope depends on how long the object should exist and how it is used. For example, singleton is suitable for stateless services, while prototype is suitable for stateful objects that should not be shared.