Basic Concept
Spring Setup
Spring Boot
Spring Bean Life Cycle with Explanation
In Spring Framework, a bean is simply an object that is managed by the Spring IoC container. The lifecycle of a bean is the set of events that occur from its creation until its destruction.
Phases of Spring bean lifecycle
The Spring bean lifecycle can be divided into three phases: instantiation, configuration, and destruction.
- Instantiation: In this phase, Spring IoC container creates the instance of the bean. Spring Framework supports several ways of instantiating a bean, such as through a constructor, a static factory method, or an instance factory method.
- Configuration: In this phase, SpringnIoC container configures the newly created bean. This includes performing dependency injection, applying any bean post-processors, and registering any initialization and destruction call-backs.
- Destruction: In this phase, Spring IoC container destroys the bean instance. It is the last phase of the Spring bean lifecycle.
Spring bean lifecycle annotations
In addition to these three phases, Spring Framework also provides several callbacks that allow developers to specify custom initialization and destruction logic for a bean. These callbacks include:
- @PostConstruct: Invoked after the bean has been constructed and all dependencies have been injected
- @init-method: Specifies a method to be called after the bean has been constructed and all dependencies have been injected • destroy-method: Specifies a method to be called just before the bean is destroyed.
- @PreDestroy: Invoked before the bean is destroyed.
The Spring bean lifecycle is controlled by the Spring IoC container, which creates, configures, and manages the lifecycle of the beans. Developers can take advantage of the bean lifecycle callbacks to add custom initialization and destruction logic to their beans, making it easier to manage the lifecycle of their objects and ensuring that resources are properly.
Spring bean lifecycle example using annotations
MyBean.java
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
public class MyBean {
// Phase 1: Instantiation (Constructor)
public MyBean() {
System.out.println("Step 1: Bean Instantiated");
}
// Phase 2: Initialization
@PostConstruct
public void init() {
System.out.println("Step 2: Bean Initialized");
// Perform custom initialization logic here
}
// Phase 4: Destruction
@PreDestroy
public void destroy() {
System.out.println("Step 4: Bean Destroyed");
// Perform custom destruction logic here
}
}
AppConfig.java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
public MyBean myBean() {
return new MyBean();
}
}
Aamir Shayan
Software Engineer