Sobes.tech
Middle

Tell about the lifecycle of a bean in Spring.

sobes.tech AI

Answer from AI

The lifecycle of a bean in Spring begins with the creation of an instance of a class managed by the Spring container. The main stages are:

  1. Bean creation — the container creates an object using the constructor.
  2. Dependency injection — Spring injects necessary dependencies (via constructor, setters, or fields).
  3. Processing interfaces BeanNameAware, BeanFactoryAware, etc. — if the bean implements these interfaces, Spring calls the corresponding methods to pass the context.
  4. Calling @PostConstruct or init-method — after setting all properties, initialization methods are called.
  5. Using the bean — the bean is ready for use in the application.
  6. Shutdown — when the container shuts down, methods annotated with @PreDestroy or destroy-method are called to clean up resources.

Example using annotations:

@Component
public class MyBean {

    @PostConstruct
    public void init() {
        System.out.println("Bean initialization");
    }

    @PreDestroy
    public void cleanup() {
        System.out.println("Cleanup before destruction");
    }
}

Thus, Spring manages the full lifecycle of a bean, ensuring creation, initialization, usage, and destruction.

Tell about the lifecycle of a bean in Spring. — Java - sobes.tech