Sobes.tech
Junior — Middle

Can you list the different scopes of beans in Spring and their features?

sobes.tech AI

Answer from AI

In Spring, there are several main scopes for beans, each defining the lifecycle and accessibility of bean instances:

  • singleton (default): one bean instance is created for the entire Spring container. All requests to this bean receive the same object.
  • prototype: a new instance is created for each request to the bean. The container does not manage the lifecycle after creation.
  • request: the bean exists for the duration of a single HTTP request. Used in web applications.
  • session: the bean is tied to the user's HTTP session and exists as long as the session is active.
  • application: the bean exists within the scope of the ServletContext, i.e., for the entire lifecycle of the web application.
  • websocket: the bean exists for the duration of the WebSocket session.

Example of declaring a bean with the prototype scope:

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

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