Middle
What is the lifecycle of an object created with Spring?
sobes.tech AI
Answer from AI
- Creating an instance: The Spring IoC container creates an object instance by calling the constructor.
- Dependency injection: The container injects dependencies into the object (for example, using
@Autowired). - Calling
setBeanName: If the bean implementsBeanNameAware, thesetBeanNamemethod is called, passing the bean's name. - Calling
setBeanFactory: If the bean implementsBeanFactoryAware, thesetBeanFactorymethod is called, passing theBeanFactory. - Calling
setApplicationContext: If the bean implementsApplicationContextAware, thesetApplicationContextmethod is called, passing theApplicationContext. - Calling
postProcessBeforeInitialization: The container calls thepostProcessBeforeInitializationmethod on allBeanPostProcessors applied to this bean. - Calling
afterPropertiesSet: If the bean implementsInitializingBean, theafterPropertiesSetmethod is called. - Calling custom initialization method: If an initialization method is specified in the bean configuration (for example, via
@PostConstructorinit-method), it is called. - Calling
postProcessAfterInitialization: The container calls thepostProcessAfterInitializationmethod on allBeanPostProcessors applied to this bean. The bean is now fully ready for use. - Using the bean: The bean is used by the application.
- Calling
destroy: Before destroying the container or when removing the bean, thedestroymethod is called if the bean implementsDisposableBean. - Calling custom destruction method: If a destruction method is specified in the bean configuration (for example, via
@PreDestroyordestroy-method), it is called. - Destroying the bean: The bean is removed by the garbage collector.