Sobes.tech
Junior

What scopes in Spring do you know?

sobes.tech AI

Answer from AI

Spring Framework defines several scopes for beans:

  1. Singleton: One instance of the bean is created for the Spring container. This is the default scope.
  2. Prototype: A new instance of the bean is created each time it is requested.
  3. Request: For web applications. One instance of the bean is created per HTTP request.
  4. Session: For web applications. One instance of the bean is created per HTTP session.
  5. Application: For web applications. One instance of the bean is created for the entire ServletContext.
  6. WebSocket: For WebSocket applications. One instance of the bean is created per WebSocket session.
  7. CustomScopes: Ability to define custom scopes.

Here is an example of declaring a bean with different scopes:

// Declaration of Singleton (default)
@Component
public class SingletonBean {
    // ...
}

// Declaration of Prototype
@Component
@Scope("prototype")
public class PrototypeBean {
    // ...
}

// Declaration of Request (for web applications)
@Component
@Scope("request")
public class RequestBean {
    // ...
}

// Declaration of Session (for web applications)
@Component
@Scope("session")
public class SessionBean {
    // ...
}

Difference between Singleton and Prototype:

Property Singleton Prototype
Number of instances One per container New each request
Lifecycle management By Spring container By Spring container until creation, then user-managed
State Shared state for all calls Separate state for each instance

Scopes Request, Session, Application, and WebSocket are only applicable in web applications and are managed by the respective request or session handlers.