Sobes.tech
Junior

What areas of visibility of beans in Spring do you know?

sobes.tech AI

Answer from AI

In the Spring Framework, the following bean scopes are available:

  • singleton: A single instance of the bean is created for each Spring context. It is the default scope. Lazy initialization can be enabled.
  • prototype: A new bean instance is created each time it is requested.
  • request: A new bean instance is created for each HTTP request. Only valid within a web application context.
  • session: A new bean instance is created for each HTTP session. Only valid within a web application context.
  • application: A single bean instance is created for the entire web application context (ServletContext). Only valid within a web application context.
  • websocket: (Starting from Spring 4.0) A new bean instance is created for each WebSocket session lifecycle.

The most commonly used scopes:

Scope Description Initialization Lifecycle
singleton One instance per Spring ApplicationContext. By default at context startup (can be made lazy). Until the ApplicationContext is closed.
prototype A new instance each time the bean is requested. Each time the bean is requested. Determined by the client (who requested the bean).
request A new instance for each HTTP request. When processing the first request that includes the bean. Until the current HTTP request is completed.
session A new instance for each HTTP session. When first accessed within a session. Until the HTTP session ends.
application One instance for the entire ServletContext (web application). When the ServletContext starts (can be made lazy). Until the ServletContext is closed.
websocket A new instance for each WebSocket session lifecycle. When establishing a WebSocket session. Until the WebSocket session ends.

Example of defining a bean with a specific scope:

// Example of defining a bean with prototype scope
@Component
@Scope("prototype")
public class MyPrototypeBean {

    // ... fields and methods ...
}