Sobes.tech
Intern

What scopes (scopes) do beans have in Spring?

sobes.tech AI

Answer from AI

In the Spring Framework, the following main bean scopes (visibility areas) exist:

  • Singleton (default) — one instance of the bean 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 lives within a single HTTP request (relevant for web applications).
  • Session — the bean lives within the user's HTTP session.
  • Application — the bean lives within the ServletContext, i.e., for the entire application.
  • Websocket — the bean lives within a WebSocket session.

Example of declaring a bean with prototype scope:

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

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