Sobes.tech
Junior — Middle

What types of scope do Bean components have in Spring?

sobes.tech AI

Answer from AI

In Spring, the following are the main types of scope for Bean components:

  • singleton (default) — one instance of the bean is created for the entire Spring container. All requests receive the same object.
  • prototype — a new instance of the bean is created for each request.
  • request — the bean exists within the scope of a single HTTP request (relevant for web applications).
  • session — the bean is tied to the user's HTTP session.
  • application — the bean exists within the scope of the ServletContext, i.e., for the entire web application.
  • websocket — the bean exists within the WebSocket session.

Example of specifying scope:

@Component
@Scope("prototype")
public class MyBean {
    // ...
}

The choice of scope depends on the requirements for the bean's lifecycle and state.

What types of scope do Bean components have in… - sobes.tech