Part 9 · Fundamentals

Scopes, lifecycle and thread-safe singleton design

Prerequisites: 01-ecosystem

When is a bean ready for advised calls?

Create bean: inject dependencies; Initialize target: lifecycle callbacks; Expose bean: possibly proxied; Destroy managed bean: shutdown callbacks. Connections: Create bean to Initialize target (populate); Initialize target to Expose bean (post-process); Expose bean to Destroy managed bean (container closes)
Typical simplified lifecycle. Prototype destruction and manually created objects require separate ownership. [S17] [S18]

Goal & mental model verified

A singleton is one instance per bean definition per container. Request scope follows a web request. The container manages initialization/destruction for managed beans, with important exceptions such as prototype destruction.

[S17] [S18]

Worked example · design exercise synthesis

QuoteService may safely be a singleton when it stores only stable collaborators. A mutable currentTenant field would mix simultaneous requests; carry tenant context through an explicit request-level mechanism instead.

[S17] [S18]

Engineering decision synthesis

Keep shared service state immutable or deliberately synchronized. Choose scope by ownership and lifetime; request-scoped dependencies in singletons need appropriate proxies or lookup.

[S17] [S18]

Pitfall & diagnosis synthesis

@PostConstruct runs during initialization, before normal proxy-mediated use. Depending on transactional advice there is unsafe. Prototype cleanup is not automatically managed like singleton destruction.

[S17] [S18]

Improve & validate synthesis

Move external startup work into a suitable lifecycle stage. Test concurrent requests and shutdown; name who owns cleanup for prototype or manually created objects.

[S17] [S18]
Keep this: Scope controls lifetime; it does not grant thread safety.
Check yourself: Does singleton mean one instance across a cluster?

No. Each application container has its own singleton instances.

Sources & further reading

  1. [S17] Bean scopes

    Spring project maintainers · documentation · accessed 2026-10-09 · Documentation retrieved 2026-10-09

    Supports: Singleton per container and bean; Prototype lifecycle limits

    Read the linked section to validate the mechanism and its version-specific constraints.

  2. [S18] Bean lifecycle

    Spring project maintainers · documentation · accessed 2026-10-09 · Documentation retrieved 2026-10-09

    Supports: Initialization and destruction callbacks; Lifecycle management

    Read the linked section to validate the mechanism and its version-specific constraints.