Junior — Middle
How does Spring manage the lifecycle of beans when their configuration is done through annotation-based methods?
sobes.tech AI
Answer from AI
Spring manages the lifecycle of beans created using annotations through the IoC (Inversion of Control) container. When the application starts, Spring scans classes with annotations such as @Component, @Service, @Repository, or @Controller, and creates instances of these classes (beans).
The bean lifecycle includes the following stages:
- Creation of the instance — Spring creates the bean object.
- Dependency injection — using annotations like
@Autowired,@Inject, or through the constructor, Spring injects the necessary dependencies. - Calling initialization methods — if the bean implements the
InitializingBeaninterface or has a method annotated with@PostConstruct, these methods are called after dependencies are injected. - Using the bean — the bean is available for use in the application.
- Destroying the bean — when the context shuts down, Spring calls methods annotated with
@PreDestroyor methods from theDisposableBeaninterface.
Thus, Spring automatically manages the creation, configuration, and destruction of beans if they are configured via annotations, without the need for explicit descriptions in XML or programmatic code.