DEV Community

Cover image for Bean Lifecycle in Spring Boot
Biswas Prasana Swain
Biswas Prasana Swain

Posted on

Bean Lifecycle in Spring Boot

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

Top comments (0)