Senior
Tell about the lifecycle of a Spring Bean?
sobes.tech AI
Answer from AI
The lifecycle of a Spring Bean includes several stages:
- Creation of the instance — Spring creates the bean object using the constructor.
- Dependency Injection — Spring sets the bean's dependencies by filling fields or calling setters.
- Initialization — if the bean implements the
InitializingBeaninterface or specifies an initialization method (init-method), they are called. - Usage — the bean is ready to be used in the application.
- Destruction — when the container shuts down, Spring calls destruction methods if the bean implements
DisposableBeanor specifies adestroy-method.
Spring also supports different bean scopes (singleton, prototype, etc.), which affect the lifecycle and the lifespan of instances.
This lifecycle allows flexible management of creation, configuration, and destruction of components in the application.