Spring Bean Lifecycle Explained with Examples


Spring Framework manages the complete lifecycle of beans from creation to destruction. Understanding the Bean Lifecycle is important because it is frequently asked in Spring Boot interviews and helps developers write better enterprise applications.


In this article, we will understand how Spring creates beans, initializes them, manages dependencies and eventually destroys them when the application shuts down.


What is a Spring Bean?

A Spring Bean is an object that is created, managed and maintained by the Spring IoC Container.

Instead of manually creating objects using the new keyword, Spring creates and manages those objects for us.


Example


@Service
public class EmployeeService {

}

In this example, EmployeeService becomes a Spring Bean.


Spring Bean Lifecycle Overview

The Spring Bean lifecycle consists of multiple phases.



Bean Instantiation
       |
       v
Dependency Injection
       |
       v
@PostConstruct
       |
       v
Bean Ready For Use
       |
       v
@PreDestroy
       |
       v
Bean Destroyed

Step 1: Bean Instantiation

The Spring Container first creates the bean instance.



@Component
public class EmployeeService {

    public EmployeeService() {

        System.out.println(
            "Constructor Called"
        );

    }
}

When Spring starts, it creates an object of EmployeeService.


Step 2: Dependency Injection

After bean creation, Spring injects all required dependencies.



@Service
public class EmployeeService {

    @Autowired
    private EmployeeRepository repository;

}

Spring automatically injects EmployeeRepository into EmployeeService.


Step 3: @PostConstruct

After dependency injection is completed, Spring invokes methods marked with @PostConstruct.



@PostConstruct
public void init() {

    System.out.println(
        "Bean Initialized"
    );

}

This method executes only once after bean creation.


When Should We Use @PostConstruct?

  • Loading configuration
  • Cache initialization
  • Database pre-loading
  • Validation tasks
  • Application startup logic

Step 4: Bean Ready For Use

Once initialization is completed, the bean becomes available throughout the application.

Controllers, Services and other components can now use this bean.


Step 5: @PreDestroy

Before application shutdown, Spring invokes methods annotated with @PreDestroy.



@PreDestroy
public void cleanup() {

    System.out.println(
        "Bean Destroyed"
    );

}

This method executes before the bean is removed from memory.


When Should We Use @PreDestroy?

  • Closing database connections
  • Closing file streams
  • Stopping background threads
  • Cleaning caches
  • Releasing external resources

Complete Example


@Service
public class EmployeeService {

    public EmployeeService() {

        System.out.println(
            "Constructor Called"
        );

    }

    @PostConstruct
    public void initialize() {

        System.out.println(
            "Initialization Logic"
        );

    }

    @PreDestroy
    public void destroy() {

        System.out.println(
            "Cleanup Logic"
        );

    }
}

Output During Startup


Constructor Called
Initialization Logic

Output During Shutdown


Cleanup Logic

Using InitializingBean Interface

Spring also provides the InitializingBean interface.



@Service
public class EmployeeService
        implements InitializingBean {

    @Override
    public void afterPropertiesSet() {

        System.out.println(
            "Bean Initialized"
        );

    }
}

However, @PostConstruct is generally preferred in modern applications.


Using DisposableBean Interface


@Service
public class EmployeeService
        implements DisposableBean {

    @Override
    public void destroy() {

        System.out.println(
            "Bean Destroyed"
        );

    }
}

This method executes when the bean is being removed.


Bean Lifecycle in Spring Boot

Spring Boot uses the same lifecycle provided by the Spring Framework.


All components such as:

  • @Controller
  • @RestController
  • @Service
  • @Repository
  • @Component

follow the same lifecycle process.


Real Interview Questions

What are the phases of Spring Bean Lifecycle?

Instantiation, Dependency Injection, Initialization and Destruction.


When is @PostConstruct called?

After dependencies are injected and before the bean becomes available.


When is @PreDestroy called?

Before the bean is removed during container shutdown.


What is the difference between Constructor and @PostConstruct?

The constructor executes before dependency injection, whereas @PostConstruct executes after dependency injection.


Which is preferred: @PostConstruct or InitializingBean?

Generally @PostConstruct because it is cleaner and less coupled to Spring APIs.


Best Practices

  • Use @PostConstruct for initialization logic.
  • Use @PreDestroy for cleanup activities.
  • Avoid heavy business logic inside constructors.
  • Keep bean initialization lightweight.
  • Use dependency injection instead of manual object creation.

Frequently Asked Questions (FAQ)

Can @PostConstruct be called multiple times?

No. It executes once for each bean instance.


Can Spring manage non-bean objects?

No. Spring lifecycle management applies to Spring-managed beans only.


Can multiple beans use @PostConstruct?

Yes. Every Spring Bean can define its own initialization logic.


Conclusion

Understanding the Spring Bean Lifecycle is essential for working with Spring Boot applications. Knowing when beans are instantiated, initialized and destroyed helps developers build efficient applications and answer common Spring interview questions confidently.


Keywords

Spring Bean Lifecycle, Spring Boot Bean Lifecycle, @PostConstruct Example, @PreDestroy Example, Spring Interview Questions, Spring Framework Tutorial, Dependency Injection Spring, InitializingBean Example, DisposableBean Example, Spring Boot Internals, Spring Core Concepts, Spring Boot Interview Questions, Bean Lifecycle Example, Java Spring Tutorial, Spring Framework Architecture

Spring Bean Lifecycle Explained with Examples Spring Bean Lifecycle Explained with Examples Reviewed by 13thGhost on 12:23 AM Rating: 5

No comments:

Recommended Posts

Powered by Blogger.