Cheatsheet

Bean scopes

Key idea

The scope says how many instances of a bean the container creates and how long they live. Singleton (the default) is one per container; prototype, a new one each time it's requested; request and session, one per HTTP request or session.

Diagram (UML)

ApplicationContextCoachBoardHeatServiceTraceControllerWodTimer #1WodTimer #2WodTimer #3RequestTrace (proxy)

Key pieces

  • @Scope("singleton" | "prototype" | "request" | "session" | "application") or the constants in ConfigurableBeanFactory and WebApplicationContext
  • @RequestScope, @SessionScope, @ApplicationScope: shortcuts that already set proxyMode = TARGET_CLASS
  • ObjectProvider<T> (or jakarta.inject.Provider<T>): asks the container for the bean on every use
  • @Lookup: Spring overrides a method so it returns a fresh bean
  • @Lazy: delays the creation of a singleton until it's used

HeatService.java

@Service
public class HeatService {
    private final ObjectProvider<WodTimer> timers; // a factory handle, not a timer

    public HeatService(ObjectProvider<WodTimer> timers) {
        this.timers = timers;
    }

    public WodTimer timerForNextAthlete() {
        return timers.getObject();                 // asks the container each time: a new prototype
    }
}

Remember for the exam

  • Singleton = one instance per container (not per JVM, like the GoF Singleton pattern)
  • Singletons are created when the context starts; prototypes, when requested
  • A singleton with mutable state must be thread-safe; ideally it has no state at all
  • The container doesn't manage the end of a prototype: it calls neither @PreDestroy nor destroy-method
  • request, session and application only exist in a web context
  • To put a short-lived bean into a long-lived one, inject a proxy (proxyMode) or an ObjectProvider

Exam traps

  • Injecting a prototype into a singleton through the constructor creates it only once: the singleton always uses the same one
  • @Scope("request") without proxyMode injected into a singleton fails at startup: there's no active request
  • Closing the context doesn't destroy prototypes
  • @Lazy on the class only delays creation; if a non-lazy bean injects it, it's still created at startup (unless the injection point is @Lazy too)

← Bean scopes · Run it