Junior — Middle
Explain the process of creating, initializing, and destroying a bean in Spring Framework.
sobes.tech AI
Answer from AI
The process of working with beans in the Spring Framework involves three main stages:
-
Creation (Instantiation) — Spring creates an instance of the bean class, usually by calling the constructor.
-
Initialization — after creation, Spring performs dependency injection, sets properties, calls methods annotated with annotations like @PostConstruct, and applies any BeanPostProcessors for additional configuration.
-
Destruction — when the Spring context is shutting down, it calls cleanup methods, such as those annotated with @PreDestroy, or methods specified in the configuration, to properly release resources.
Example:
@Component
public class MyBean {
@PostConstruct
public void init() {
System.out.println("Bean initialized");
}
@PreDestroy
public void cleanup() {
System.out.println("Bean is being destroyed");
}
}
Thus, Spring manages the bean's lifecycle, ensuring its creation, configuration, and proper shutdown.