Senior
What is the lifecycle of a bean in Spring?
sobes.tech AI
Answer from AI
The lifecycle of a bean in Spring includes several stages:
- Creation of the instance — Spring creates the bean object, usually using reflection.
- Dependency injection — dependencies specified in the configuration are injected.
- Callback processing:
- If the bean implements
BeanNameAware, thesetBeanName()method is called. - If it implements
BeanFactoryAware,setBeanFactory()is called. - If it implements
ApplicationContextAware,setApplicationContext()is called.
- If the bean implements
- Annotation and configuration processing — for example,
@PostConstruct. - Initialization — the
afterPropertiesSet()method from theInitializingBeaninterface or a custom init method is called. - Bean usage — the bean is ready for use.
- Destruction — when the context is closed, the
destroy()method from theDisposableBeaninterface or a custom destroy method is called.
Example of bean initialization with a custom init method:
@Component
public class MyBean {
@PostConstruct
public void init() {
// initialization code
}
}