0
0
Spring Bootframework~15 mins

Bean lifecycle overview in Spring Boot - Deep Dive

Choose your learning style9 modes available
Overview - Bean lifecycle overview
What is it?
In Spring Boot, a bean is an object managed by the framework's container. The bean lifecycle is the series of steps a bean goes through from creation to destruction. This lifecycle includes creation, initialization, usage, and finally destruction. Understanding this helps you control how your application components behave and interact.
Why it matters
Without managing the bean lifecycle, your application could waste resources, have bugs due to improper setup, or leak memory by not cleaning up. The lifecycle ensures beans are ready when needed and properly cleaned up, making your app efficient and reliable. It also allows customization at key points, improving flexibility and control.
Where it fits
Before learning bean lifecycle, you should understand basic Spring Boot concepts like dependency injection and configuration. After mastering lifecycle, you can explore advanced topics like custom bean post-processors, scopes, and application context events.
Mental Model
Core Idea
A Spring bean's lifecycle is like a carefully managed journey from birth through growth to retirement, with clear stages where you can step in to customize behavior.
Think of it like...
Imagine a plant growing in a garden: it is planted (created), watered and cared for (initialized), grows and produces fruit (used), and eventually is pruned or removed (destroyed). Each stage needs attention to keep the garden healthy.
┌───────────────┐
│ Bean Creation │
└──────┬────────┘
       │
┌──────▼────────┐
│ Initialization│
└──────┬────────┘
       │
┌──────▼────────┐
│   Usage       │
└──────┬────────┘
       │
┌──────▼────────┐
│  Destruction  │
└───────────────┘
Build-Up - 7 Steps
1
FoundationWhat is a Spring Bean?
🤔
Concept: Introduce the basic idea of a bean as a managed object in Spring.
A Spring bean is simply an object that Spring creates and manages for you. Instead of creating objects yourself with 'new', Spring does it and keeps track of them. Beans are the building blocks of your application.
Result
You understand that beans are objects controlled by Spring, not manually created.
Knowing that Spring manages objects helps you see why lifecycle control is possible and useful.
2
FoundationBean Creation and Dependency Injection
🤔
Concept: Explain how Spring creates beans and injects dependencies.
When your app starts, Spring looks for bean definitions and creates instances. It also fills in any dependencies those beans need, like other beans or configuration values. This happens automatically based on your setup.
Result
Beans are created and ready with their dependencies set before use.
Understanding creation and injection clarifies the first lifecycle phase and why it matters.
3
IntermediateBean Initialization Phase
🤔Before reading on: do you think initialization happens before or after dependencies are set? Commit to your answer.
Concept: Introduce the initialization step where beans prepare themselves after creation and injection.
After a bean is created and dependencies are injected, Spring calls initialization methods. These can be methods you define to set up resources or validate state. You can use annotations like @PostConstruct or implement interfaces like InitializingBean.
Result
Beans are fully prepared and ready to perform their tasks.
Knowing initialization happens after injection helps you place setup code correctly for reliable behavior.
4
IntermediateBean Usage and Scope
🤔Before reading on: do you think all beans live forever or can their lifespan vary? Commit to your answer.
Concept: Explain how beans are used during app runtime and how their scope affects lifecycle length.
Once initialized, beans are used by your app to perform work. Beans can have different scopes like singleton (one instance) or prototype (new instance each time). The scope controls how long a bean lives and when it is reused or recreated.
Result
You understand that bean lifespan depends on scope and usage patterns.
Recognizing scope's role prevents bugs related to unexpected bean sharing or recreation.
5
IntermediateBean Destruction and Cleanup
🤔
Concept: Describe how Spring cleans up beans before app shutdown or when beans are no longer needed.
When the app stops or a bean is removed, Spring calls destruction methods to release resources. You can define cleanup code with @PreDestroy or DisposableBean interface. This prevents resource leaks like open files or connections.
Result
Beans are properly cleaned up, avoiding resource waste.
Understanding destruction ensures you write cleanup code to keep apps stable and efficient.
6
AdvancedCustomizing Lifecycle with BeanPostProcessor
🤔Before reading on: do you think you can change a bean before and after initialization? Commit to your answer.
Concept: Introduce BeanPostProcessor to modify beans during lifecycle phases.
Spring allows you to hook into the lifecycle by implementing BeanPostProcessor. This lets you run code before and after a bean's initialization method. It's useful for adding proxies, logging, or modifying bean properties dynamically.
Result
You can customize bean behavior globally without changing bean code.
Knowing about BeanPostProcessor unlocks powerful extension points for advanced customization.
7
ExpertLifecycle Surprises: Lazy and Conditional Beans
🤔Before reading on: do you think all beans are created at startup or can some be delayed? Commit to your answer.
Concept: Explain how lazy initialization and conditional beans affect lifecycle timing and behavior.
By default, singleton beans are created at startup, but you can mark beans as lazy to create them only when needed. Also, conditional beans load only if certain conditions are met. These features change when lifecycle phases happen and can improve startup time or adapt behavior.
Result
You understand how lifecycle timing can be controlled for performance and flexibility.
Knowing lifecycle timing nuances helps avoid bugs and optimize app startup and resource use.
Under the Hood
Spring uses a container called ApplicationContext to manage beans. When the app starts, it reads bean definitions and creates bean instances using reflection. It injects dependencies by matching types or names. Then it calls lifecycle callbacks like initialization and destruction methods. BeanPostProcessors wrap or modify beans before and after initialization. The container tracks bean scopes to manage their lifespan and cleans up beans on shutdown.
Why designed this way?
Spring was designed to simplify Java development by managing object creation and dependencies automatically. The lifecycle model provides clear extension points for customization without changing bean code. This design balances flexibility with control, allowing developers to focus on business logic. Alternatives like manual object management were error-prone and less scalable.
┌─────────────────────────────┐
│       ApplicationContext    │
│ ┌───────────────┐           │
│ │ BeanFactory   │           │
│ │ ┌───────────┐ │           │
│ │ │ Reflection│ │           │
│ │ └────┬──────┘ │           │
│ │      │        │           │
│ │  Create Bean  │           │
│ │      │        │           │
│ │ Inject Dependencies       │
│ │      │        │           │
│ │ Call BeanPostProcessors   │
│ │      │        │           │
│ │ Call Initialization       │
│ │      │        │           │
│ │ Bean Ready for Use        │
│ │      │        │           │
│ │ Call Destruction on Close │
│ └───────────────┘           │
└─────────────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do you think prototype-scoped beans are destroyed by Spring automatically? Commit to yes or no.
Common Belief:Prototype beans are destroyed automatically by Spring like singleton beans.
Tap to reveal reality
Reality:Spring does not manage the destruction of prototype beans; the client code must clean them up.
Why it matters:Assuming automatic destruction causes resource leaks because cleanup code is never called.
Quick: Do you think @PostConstruct runs before dependencies are injected? Commit to yes or no.
Common Belief:@PostConstruct methods run before dependency injection happens.
Tap to reveal reality
Reality:@PostConstruct methods run after all dependencies are injected.
Why it matters:Running setup code too early can cause null pointer errors or incomplete initialization.
Quick: Do you think BeanPostProcessor affects bean creation order? Commit to yes or no.
Common Belief:BeanPostProcessors change the order in which beans are created.
Tap to reveal reality
Reality:BeanPostProcessors do not change creation order; they modify beans after creation but before use.
Why it matters:Misunderstanding this can lead to incorrect assumptions about bean dependencies and lifecycle timing.
Quick: Do you think lazy beans are created at startup? Commit to yes or no.
Common Belief:Lazy beans are created when the application starts, just like other beans.
Tap to reveal reality
Reality:Lazy beans are created only when first requested, delaying their lifecycle phases.
Why it matters:Expecting lazy beans to be ready at startup can cause runtime errors or delays.
Expert Zone
1
BeanPostProcessors run for every bean, including infrastructure beans, so filtering is often needed to avoid side effects.
2
Destruction callbacks for singleton beans happen only when the ApplicationContext closes, which may be late in the app lifecycle.
3
Custom scopes can define completely different lifecycle rules, requiring careful management of creation and destruction.
When NOT to use
Avoid relying on lifecycle callbacks for critical business logic; instead, use explicit service methods. For very simple apps, manual object management or lightweight frameworks may be simpler. Also, avoid prototype scope if you need Spring to manage full lifecycle including destruction.
Production Patterns
In production, lifecycle hooks are used to manage resource pools, open/close connections, and apply proxies for transactions or security. BeanPostProcessors enable features like AOP and monitoring. Lazy initialization improves startup time for large apps. Conditional beans allow environment-specific configurations.
Connections
Object-Oriented Programming Constructors and Destructors
Bean lifecycle phases correspond to object creation and destruction in OOP.
Understanding constructors and destructors helps grasp why initialization and destruction callbacks exist in Spring beans.
Operating System Process Lifecycle
Both have stages: creation, running, waiting, and termination.
Seeing bean lifecycle like a process lifecycle clarifies the importance of managing resources and cleanup.
Project Management Phases
Bean lifecycle stages mirror project phases: initiation, planning, execution, closure.
Recognizing lifecycle as phases with checkpoints helps plan and control complex systems.
Common Pitfalls
#1Forgetting to release resources in destruction methods.
Wrong approach:@PreDestroy public void cleanup() { // no resource release here }
Correct approach:@PreDestroy public void cleanup() { resource.close(); }
Root cause:Misunderstanding that destruction callbacks must explicitly release resources.
#2Using prototype scope but expecting Spring to call @PreDestroy.
Wrong approach:@Scope("prototype") public class MyBean { @PreDestroy public void cleanup() { /* cleanup code */ } }
Correct approach:Manage prototype bean lifecycle manually; Spring does not call @PreDestroy for prototype beans.
Root cause:Assuming Spring manages full lifecycle for all scopes.
#3Placing initialization code in constructor instead of @PostConstruct.
Wrong approach:public MyBean() { setup(); // depends on injected dependencies }
Correct approach:@PostConstruct public void init() { setup(); }
Root cause:Not realizing dependencies are injected after constructor runs.
Key Takeaways
Spring beans go through a clear lifecycle: creation, initialization, usage, and destruction.
Lifecycle callbacks like @PostConstruct and @PreDestroy let you customize setup and cleanup safely.
Bean scope controls how long a bean lives and when lifecycle phases happen.
BeanPostProcessors provide powerful hooks to modify beans globally during lifecycle.
Understanding lifecycle timing and scope prevents common bugs and resource leaks.