Senior
What is the lifecycle of a Spring bean?
sobes.tech AI
Answer from AI
The lifecycle of a Spring bean includes several stages:
- Creation of the instance — Spring creates the bean object, usually via the constructor.
- Dependency injection — autowiring occurs, and property values are set.
- Callback processing — if the bean implements interfaces like
BeanNameAware,BeanFactoryAware, etc., the corresponding methods are called. - Initialization — a method annotated with
@PostConstructor theafterPropertiesSet()method from theInitializingBeaninterface is invoked. - Bean usage — the bean is ready for use in the application.
- Destruction — when the context is closed, methods annotated with
@PreDestroyor thedestroy()method from theDisposableBeaninterface are called.
Example using annotations:
@Component
public class MyBean {
@PostConstruct
public void init() {
// initialization after dependency injection
}
@PreDestroy
public void cleanup() {
// resource cleanup before destruction
}
}