Middle
Tell about the lifecycle of a bean in Spring.
sobes.tech AI
Answer from AI
The lifecycle of a bean in Spring begins with the creation of an instance of a class managed by the Spring container. The main stages are:
- Bean creation — the container creates an object using the constructor.
- Dependency injection — Spring injects necessary dependencies (via constructor, setters, or fields).
- Processing interfaces BeanNameAware, BeanFactoryAware, etc. — if the bean implements these interfaces, Spring calls the corresponding methods to pass the context.
- Calling @PostConstruct or init-method — after setting all properties, initialization methods are called.
- Using the bean — the bean is ready for use in the application.
- Shutdown — when the container shuts down, methods annotated with @PreDestroy or destroy-method are called to clean up resources.
Example using annotations:
@Component
public class MyBean {
@PostConstruct
public void init() {
System.out.println("Bean initialization");
}
@PreDestroy
public void cleanup() {
System.out.println("Cleanup before destruction");
}
}
Thus, Spring manages the full lifecycle of a bean, ensuring creation, initialization, usage, and destruction.