Spring Bean lifecycle
The lifecycle of a Spring bean refers to the various stages a bean goes through from its creation to its destruction. The lifecycle of a bean is managed by the Spring framework, and it consists of the following phases:
Instantiation: Spring creates an instance of the bean using a constructor or a factory method.
Dependency Injection: Spring injects any dependencies the bean may have, either through constructor arguments or setter methods.
Post-Processing: If any bean post-processors are registered, they will be applied to the bean to allow for any additional configuration.
Initialization: If the bean implements the
InitializingBean
interface, theafterPropertiesSet()
method will be called, allowing for any additional initialization. If a@PostConstruct
annotated method is present, it will also be called.Ready for Use: The bean is now fully initialized and ready for use by the application.
Destruction: When the application context is closed, or when the bean is no longer required, the
DisposableBean
interface'sdestroy()
method will be called, allowing for any necessary cleanup. If a@PreDestroy
annotated method is present, it will also be called.
Note: The order of these phases can be influenced by various bean configuration settings and custom BeanPostProcessors.
InitializingBean
interface and has a @PostConstruct
annotated method:import javax.annotation.PostConstruct;
import org.springframework.beans.factory.InitializingBean;
public class ExampleBean implements InitializingBean {
private String message;
public ExampleBean(String message) {
this.message = message;
}
@PostConstruct
public void init() {
System.out.println("@PostConstruct method called");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("afterPropertiesSet method called");
}
public String getMessage() {
return message;
}
}
DisposableBean
interface and has a @PreDestroy
annotated method:import javax.annotation.PreDestroy;
import org.springframework.beans.factory.DisposableBean;
public class ExampleBean implements DisposableBean {
private String message;
public ExampleBean(String message) {
this.message = message;
}
@PreDestroy
public void cleanup() {
System.out.println("@PreDestroy method called");
}
@Override
public void destroy() throws Exception {
System.out.println("destroy method called");
}
public String getMessage() {
return message;
}
}
Leave a Comment