Junior — Middle
Can you explain the lifecycle stages of a Spring component used in applications?
sobes.tech AI
Answer from AI
The lifecycle of a Spring component (e.g., a bean) includes several stages:
- Creation of the instance — Spring creates the bean object, usually through the constructor.
- Dependency Injection — Spring sets the necessary dependencies, for example, via setters or constructor.
- Initialization — initialization methods are called if defined (e.g., methods annotated with
@PostConstructor implementing theInitializingBeaninterface). - Usage — the bean is ready to work and is used in the application.
- Destruction — when the context is shutting down, Spring calls destruction methods (e.g., annotated with
@PreDestroyor implementingDisposableBean), where resources can be released.
Example with annotations:
@Component
public class MyBean {
@PostConstruct
public void init() {
// initialization code
}
@PreDestroy
public void cleanup() {
// cleanup code
}
}
Thus, Spring manages the complete lifecycle of components, providing convenient management of dependencies and resources.