Skip to main content
PreparationZone Logo
PrepZone

Bean Scopes and Lifecycle

Singleton, prototype, request and session scopes — and the callbacks between birth and destruction.

Pass checkpoint below

Why this matters

  • Injecting request-specific state into a singleton bean is a common bug that causes data leaks between BookStore customers.
  • Understanding lifecycle callbacks lets you open resources at startup and close them on shutdown cleanly.
  • Scope questions appear in interviews because the wrong scope silently corrupts concurrent requests.

Singleton by default

L1 · Fresher

One BookService instance serves all requests unless you change scope. Stateless services should stay singleton — they are cheap and thread-safe when they do not hold per-user state.

Web scopes

L2 · Intermediate

@Scope("request") and session tie beans to HTTP lifecycle. They need a web context and are easy to misuse in async threads that leave the request.

Lifecycle callbacks

L3 · Advanced

@PostConstruct and @PreDestroy run after injection and before shutdown. Use them for cheap initialization and resource cleanup — not for heavy business logic.

Prototype scope pitfalls

L4 · Expert

Prototype beans create a new instance per injection point. Injecting a prototype into a singleton effectively shares one instance unless you use ObjectProvider or method injection.

Singleton scope (default)

Java
// learn:fragment
@Service  // scope defaults to singleton
public class BookService { ... }

One instance per ApplicationContext. Every HTTP request shares the same BookService. This is correct for stateless services that delegate to repositories.

Never store request data in a singleton field:

Java
// learn:fragment
@Service
public class BookService {
    private String currentUser;  // BUG: shared across all requests!
}

Prototype scope

Java
// learn:fragment
@Component
@Scope("prototype")
public class SearchCriteriaBuilder {
    private List<String> filters = new ArrayList<>();
    // each injection gets a fresh instance
}

A new instance every time the bean is requested. Useful for builder objects or per-operation state. Spring does not manage prototype destruction — you own cleanup.

The rest of this guide is part of Pro

Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.

Still to come · 6 sections

  • Web scopes
  • Lifecycle callbacks
  • Startup ordering with @DependsOn
  • Lazy initialisation
  • Scope in practice for BookStore
  • Observing bean creation

Test yourself

Answer these before moving on — recall is what makes it stick.