Spring Bean Lifecycle
spring bean lifecycle every spring bean goes through a well-defined lifecycle: instantiation → dependency injection → initialization → use → destruction. hooks
Introduction
Every Spring bean goes through a well-defined lifecycle: instantiation → dependency injection → initialization → use → destruction. Hooks like @PostConstruct, InitializingBean and @PreDestroy let you run setup and teardown logic.
Informative example
Lifecycle callbacks:
@Componentpublic class CacheWarmer {private final DataSource ds;@PostConstructvoid warmCache() {log.info("Loading reference data...");// runs after DI, before bean is used}@PreDestroyvoid shutdown() {log.info("Flushing cache...");// runs on context shutdown}}// Bean scopes@Scope("prototype") // new instance every injection@Scope("request") // one per HTTP request (web apps)
Best practices
- Keep @PostConstruct logic fast — it blocks context startup.
- Use ApplicationListener for cross-cutting startup, not every bean.
- Default scope is singleton — understand implications for mutable state.
Purpose of this lesson
Master Spring Bean Lifecycle so you can apply it confidently in production Java code, technical interviews, and code reviews.
Step-by-step explanation
- Understand the core idea behind Spring Bean Lifecycle.
- Walk through the runnable example and tweak it in the playground.
- Apply the pattern in a small Spring Boot or CLI exercise of your own.
- Re-read the common mistakes and interview Q&A to lock the concept in.
Interactive workflow diagram
Identify use case
Recognize when spring bean lifecycle is the right tool for the problem.
Debugging tips
- Bean not injected? Check component scan package — @SpringBootApplication only scans its package and below.
Optimization strategies
- Profile before optimizing — JFR (Java Flight Recorder) and async-profiler reveal real hotspots.
- Prefer immutable data and stream pipelines over hand-rolled loops when readability matters.
- Reach for the right JDK collection (ArrayList vs LinkedList vs ArrayDeque) before writing custom data structures.
Enterprise example
Teams at Netflix, Uber and Goldman Sachs apply Spring Bean Lifecycle daily — usually wrapped behind Spring Boot services with observability hooks (Micrometer + OpenTelemetry).
Interview questions & answers
Q1Explain Spring Bean Lifecycle in one minute.
Q2When would you avoid Spring Bean Lifecycle?
Summary
In this lesson you learned Spring Bean Lifecycle — the concept, syntax, a runnable example, and the production pitfalls to avoid. Apply it in the playground before moving on.