Sobes.tech
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:

  1. Creation of the instance — Spring creates the bean object, usually using reflection.
  2. Dependency injection — dependencies specified in the configuration are injected.
  3. Callback processing:
    • If the bean implements BeanNameAware, the setBeanName() method is called.
    • If it implements BeanFactoryAware, setBeanFactory() is called.
    • If it implements ApplicationContextAware, setApplicationContext() is called.
  4. Annotation and configuration processing — for example, @PostConstruct.
  5. Initialization — the afterPropertiesSet() method from the InitializingBean interface or a custom init method is called.
  6. Bean usage — the bean is ready for use.
  7. Destruction — when the context is closed, the destroy() method from the DisposableBean interface 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
    }
}