Senior
Tell us about the lifecycle of a bean in Spring.
sobes.tech AI
Answer from AI
The lifecycle of a bean in Spring includes several stages:
- Creation of the instance — Spring creates the bean object, usually through the constructor.
- Dependency injection — Spring injects the necessary dependencies (via constructor, setters, or fields).
- Processing interfaces like BeanNameAware, BeanFactoryAware, etc. — if the bean implements these interfaces, Spring calls the corresponding methods, passing the context.
- Calling @PostConstruct methods or afterPropertiesSet() — initializing the bean after all properties are set.
- Using the bean — the bean is ready for use in the application.
- Destroying the bean — when the context is shutting down, Spring calls methods annotated with @PreDestroy or destroy() from the DisposableBean interface.
Example using annotations:
@Component
public class MyBean {
@PostConstruct
public void init() {
// initialization after creation and dependency injection
}
@PreDestroy
public void cleanup() {
// resource cleanup before destruction
}
}
Thus, Spring manages the bean's lifecycle, ensuring creation, initialization, usage, and proper destruction.