SpringBoot BeanLife Cycle
SpringBoot BeanLife Cycle
java
Copy code
import javax.annotation.PostConstruct;
public class MyBean {
@PostConstruct
public void init() {
System.out.println("Bean initialized");
}
}
5. Ready for Use
• Once the initialization is done, the bean is fully ready and can be used
within the Spring context.
• The bean can now be injected into other components, accessed through
Spring’s Dependency Injection mechanism.
6. Destruction
• When the Spring container is shut down or the bean is no longer needed, it
is destroyed.
• If the bean implements DisposableBean, Spring calls the destroy() method.
• If the bean has a method annotated with @PreDestroy, that method will be
invoked before the bean is destroyed.
Example of using @PreDestroy:
java
Copy code
import javax.annotation.PreDestroy;
public class MyBean {
@PreDestroy
public void cleanup() {
System.out.println("Bean destroyed");
}
}
Spring Bean Lifecycle Summary
1. Bean Creation (Instantiation): Spring instantiates the bean.
2. Dependency Injection: Spring injects the required dependencies into the
bean.
3. Bean Post Processing: BeanPostProcessors modify the bean before and after
initialization.
4. Initialization: Spring initializes the bean by invoking @PostConstruct or
InitializingBean.
5. Ready for Use: The bean is now available for use in the application.
6. Destruction: On application shutdown, the @PreDestroy method or
DisposableBean interface is called to clean up resources.
Customizing the Bean Lifecycle
You can customize different stages of the bean lifecycle:
• Initialization: Use @PostConstruct, InitializingBean, or custom initMethod.
• Destruction: Use @PreDestroy, DisposableBean, or custom destroyMethod.
By leveraging these phases and customizing them, Spring Boot allows a lot of
flexibility in controlling how beans are managed within the application context.