🔄

Spring Boot: Bean Scopes

Jul 16, 2024

Spring Boot: Bean Scopes

Prerequisites

  • Understanding of Bean and its lifecycle

Types of Bean Scopes in Spring Boot

Singleton

  • Default scope
  • Only one instance created per IOC (or per application)
  • Eagerly initialized by IOC
  • Example:
    • Class without scope definition defaults to singleton
    • Can explicitly declare with @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
    • During application startup:
      • Rest controller class is initialized
      • Dependencies (e.g., User) are injected and initialized
      • Singleton instances are reused across the application

Prototype

  • New object created each time it is needed
  • Lazily initialized
  • Example:
    • Marked with @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    • Dependencies might themselves be singleton (e.g., Student), in which case they are initialized eagerly
    • During HTTP request, new instances are created
    • Each HTTP request or method call results in a new instance

Request

  • New instance created for each HTTP request
  • Lazily initialized
  • Example:
    • Marked with @Scope(WebApplicationContext.SCOPE_REQUEST)
    • Tied to a specific HTTP request
    • Objects created only when needed within the scope of a single request
  • Special consideration:
    • If a singleton bean injects a request-scoped bean, use a proxy mode (proxyMode = ScopedProxyMode.TARGET_CLASS)
    • This creates a proxy during application start, which is replaced with the actual request-scoped instance during HTTP requests

Session

  • One instance created per HTTP session
  • Lazily initialized
  • Example:
    • Marked with @Scope(WebApplicationContext.SCOPE_SESSION)
    • Multiple HTTP requests within the same session share the instance
    • New instance is created when a new session is initiated
    • Can configure session expiry time in application.properties
  • Scenario:
    • First HTTP session request initializes session-scoped beans
    • Subsequent requests in the same session reuse these beans
    • Ending session clears beans and subsequent session initiates new instances

Application

  • Similar to singleton but shared across multiple IOC containers
  • Use case is rare: Not commonly encountered but useful in multi-IOC scenarios

Summary

  • Singleton: One per IOC, eagerly initialized
  • Prototype: New instance per use, lazily initialized
  • Request: New instance per HTTP request, lazily initialized
  • Session: New instance per HTTP session, lazily initialized
  • Application: One instance shared across multiple IOCs, similar to singleton but for multiple IOCs