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)
sequenceDiagram participant C as ApplicationContext participant S as CoachBoard «singleton» participant H as HeatService «singleton» participant T as WodTimer «prototype» Note over C,S: startup: singletons are created once C->>T: new WodTimer #1 C->>S: new CoachBoard(timer #1) C->>H: new HeatService(ObjectProvider) Note over S,T: every call returns timer #1 (frozen) S->>S: timerForNextAthlete() → #1 H->>C: timers.getObject() C->>T: new WodTimer #2 H->>C: timers.getObject() C->>T: new WodTimer #3 Note over C,T: close(): @PreDestroy only for singletons
Key pieces
@Scope("singleton" | "prototype" | "request" | "session" | "application")or the constants inConfigurableBeanFactoryandWebApplicationContext@RequestScope,@SessionScope,@ApplicationScope: shortcuts that already setproxyMode = TARGET_CLASSObjectProvider<T>(orjakarta.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
@PreDestroynordestroy-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 anObjectProvider
Exam traps
- Injecting a prototype into a singleton through the constructor creates it only once: the singleton always uses the same one
@Scope("request")withoutproxyModeinjected into a singleton fails at startup: there's no active request- Closing the context doesn't destroy prototypes
@Lazyon the class only delays creation; if a non-lazy bean injects it, it's still created at startup (unless the injection point is@Lazytoo)