Sobes.tech
Senior

Tell us about 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 through the constructor.
  2. Dependency injection — Spring injects the necessary dependencies (via constructor, setters, or fields).
  3. Processing interfaces like BeanNameAware, BeanFactoryAware, etc. — if the bean implements these interfaces, Spring calls the corresponding methods, passing the context.
  4. Calling @PostConstruct methods or afterPropertiesSet() — initializing the bean after all properties are set.
  5. Using the bean — the bean is ready for use in the application.
  6. Destroying the bean — when the context is shutting down, Spring calls methods annotated with @PreDestroy or destroy() from the DisposableBean interface.

Example using annotations:

@Component
public class MyBean {

    @PostConstruct
    public void init() {
        // initialization after creation and dependency injection
    }

    @PreDestroy
    public void cleanup() {
        // resource cleanup before destruction
    }
}

Thus, Spring manages the bean's lifecycle, ensuring creation, initialization, usage, and proper destruction.