惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
V2EX
IT之家
IT之家
博客园 - 叶小钗
雷峰网
雷峰网
T
Tailwind CSS Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
S
SegmentFault 最新的问题
Apple Machine Learning Research
Apple Machine Learning Research
爱范儿
爱范儿
博客园 - 【当耐特】
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
大猫的无限游戏
大猫的无限游戏
Last Week in AI
Last Week in AI
月光博客
月光博客
酷 壳 – CoolShell
酷 壳 – CoolShell
Jina AI
Jina AI
博客园 - Franky
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
宝玉的分享
宝玉的分享
阮一峰的网络日志
阮一峰的网络日志
Hugging Face - Blog
Hugging Face - Blog
博客园 - 司徒正美

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Bean Lifecycle in Spring Boot
Biswas Prasa · 2026-05-18 · via DEV Community

A polite tour through how Spring creates, uses, and destroys your objects while you pretend you are in control.

Spring Boot applications are mostly made of beans.

A bean is just an object that Spring manages for you.
You write the class. Spring handles the birth, setup, wiring, and death of the object. Like a very organized hotel manager for Java classes. Humanity invented dependency injection because manually creating objects became emotionally exhausting.

Let’s understand the Bean Lifecycle using simple questions and answers.


First Question: What is a Bean?

Suppose we have this service:

@Service
public class EmailService {

    public void sendEmail() {
        System.out.println("Sending email...");
    }
}

Enter fullscreen mode Exit fullscreen mode

@Service tells Spring:

"Please create this object and manage it for me."

That object becomes a Spring Bean.


Second Question: What does “Lifecycle” mean?

Lifecycle means:

  1. Bean is created
  2. Bean gets dependencies
  3. Bean gets initialized
  4. Bean is used
  5. Bean gets destroyed

Like this:

Create → Inject Dependencies → Initialize → Use → Destroy

Enter fullscreen mode Exit fullscreen mode

Spring does all this automatically.

Because apparently developers once enjoyed writing 200 lines of setup code just to create one object.


Third Question: When does Spring create a Bean?

Spring creates beans when the application starts.

Example:

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

Enter fullscreen mode Exit fullscreen mode

When run() happens:

  • Spring scans classes
  • Finds annotations like @Component, @Service
  • Creates objects
  • Stores them inside the Spring Container

The container is basically Spring’s giant object warehouse.


Fourth Question: What happens first in Bean Lifecycle?

Step 1: Bean Instantiation

Spring creates the object.

Example:

@Service
public class UserService {

    public UserService() {
        System.out.println("Constructor called");
    }
}

Enter fullscreen mode Exit fullscreen mode

Output:

Constructor called

Enter fullscreen mode Exit fullscreen mode

This is the very first lifecycle step.


Fifth Question: What happens after object creation?

Step 2: Dependency Injection

Suppose this bean needs another bean.

@Service
public class NotificationService {

    public void notifyUser() {
        System.out.println("Notifying user");
    }
}

Enter fullscreen mode Exit fullscreen mode

Now inject it:

@Service
public class UserService {

    private final NotificationService notificationService;

    public UserService(NotificationService notificationService) {
        this.notificationService = notificationService;
    }
}

Enter fullscreen mode Exit fullscreen mode

Spring does this automatically.

It first creates NotificationService, then gives it to UserService.

This is called Dependency Injection.

Fancy name. Simple idea.

Dependency Injection in Bean Lifecycle


Sixth Question: Can we run code after bean creation?

Yes.

Step 3: Initialization

Sometimes we want code to run after dependencies are ready.

Example:

@Service
public class DatabaseService {

    @PostConstruct
    public void init() {
        System.out.println("Database connection initialized");
    }
}

Enter fullscreen mode Exit fullscreen mode

Output:

Database connection initialized

Enter fullscreen mode Exit fullscreen mode

@PostConstruct runs after:

  • bean creation
  • dependency injection

This is useful for:

  • opening connections
  • loading files
  • caching data

Seventh Question: What is the exact order until now?

The order is:

1. Constructor
2. Dependency Injection
3. @PostConstruct

Enter fullscreen mode Exit fullscreen mode

Example:

@Service
public class DemoService {

    public DemoService() {
        System.out.println("1. Constructor");
    }

    @PostConstruct
    public void init() {
        System.out.println("2. PostConstruct");
    }
}

Enter fullscreen mode Exit fullscreen mode

Output:

1. Constructor
2. PostConstruct

Enter fullscreen mode Exit fullscreen mode

Simple. Beautiful. Suspiciously efficient.


Eighth Question: What happens while the application is running?

Step 4: Bean is Ready to Use

Now the bean works normally.

@RestController
public class HelloController {

    private final UserService userService;

    public HelloController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/hello")
    public String hello() {
        return "Hello";
    }
}

Enter fullscreen mode Exit fullscreen mode

Spring keeps the bean alive inside the container.

By default, beans are Singleton.

Meaning:

Only one object is created for the entire application

Enter fullscreen mode Exit fullscreen mode


Ninth Question: What happens when application stops?

Step 5: Bean Destruction

Spring destroys beans gracefully.

We can run cleanup code before destruction.

Example:

@Service
public class FileService {

    @PreDestroy
    public void cleanup() {
        System.out.println("Closing files...");
    }
}

Enter fullscreen mode Exit fullscreen mode

When app shuts down:

Closing files...

Enter fullscreen mode Exit fullscreen mode

Useful for:

  • closing DB connections
  • stopping threads
  • releasing resources

Because memory leaks are the software version of leaving your kitchen gas on.


Tenth Question: What is the Full Lifecycle?

Here is the complete flow:

Spring Starts
     ↓
Bean Created
     ↓
Dependencies Injected
     ↓
@PostConstruct Runs
     ↓
Bean Ready to Use
     ↓
Application Stops
     ↓
@PreDestroy Runs
     ↓
Bean Removed

Enter fullscreen mode Exit fullscreen mode


Full Example

@Service
public class LifeCycleService {

    public LifeCycleService() {
        System.out.println("1. Constructor called");
    }

    @PostConstruct
    public void init() {
        System.out.println("2. Bean initialized");
    }

    public void doWork() {
        System.out.println("3. Bean is working");
    }

    @PreDestroy
    public void destroy() {
        System.out.println("4. Bean destroyed");
    }
}

Enter fullscreen mode Exit fullscreen mode

Possible Output:

1. Constructor called
2. Bean initialized
3. Bean is working
4. Bean destroyed

Enter fullscreen mode Exit fullscreen mode


Final Mental Model

Think of Spring like a factory manager.

You provide class blueprints.

Spring:

  • creates objects
  • connects objects together
  • prepares them
  • manages them
  • destroys them safely

You focus on business logic.

Spring handles object management.

And somewhere deep inside the framework, thousands of reflection calls whisper through the void while your app boots for 14 seconds because someone added three extra starters.


Quick Revision

Step Description
Instantiation Bean object created
Dependency Injection Required beans injected
Initialization @PostConstruct runs
Ready State Bean is used
Destruction @PreDestroy runs