Sobes.tech
Senior

What is the lifecycle of a Spring bean?

sobes.tech AI

Answer from AI

The lifecycle of a Spring bean includes several stages:

  1. Creation of the instance — Spring creates the bean object, usually via the constructor.
  2. Dependency injection — autowiring occurs, and property values are set.
  3. Callback processing — if the bean implements interfaces like BeanNameAware, BeanFactoryAware, etc., the corresponding methods are called.
  4. Initialization — a method annotated with @PostConstruct or the afterPropertiesSet() method from the InitializingBean interface is invoked.
  5. Bean usage — the bean is ready for use in the application.
  6. Destruction — when the context is closed, methods annotated with @PreDestroy or the destroy() method from the DisposableBean interface are called.

Example using annotations:

@Component
public class MyBean {

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

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