Bean Life Cycle Management

In the Spring Framework, the lifecycle of a bean is managed by the Spring container. The container is responsible for creating and initializing the bean, and also for cleaning up the bean when it's no longer needed.

Here are the different stages in the lifecycle of a bean in Spring:

  1. Bean instantiation: The container creates a new instance of the bean.

  2. Dependency injection: The container injects any required dependencies into the bean, either by constructor injection or by property injection.

  3. Initialization: If the bean implements the InitializingBean interface or defines an @PostConstruct method, the container invokes that method after all dependencies have been injected.

  4. Usage: The bean is now available for use by other components in the application.

  5. Destruction: If the bean implements the DisposableBean interface or defines an @PreDestroy method, the container invokes that method before the bean is removed from the application context.

Here's an example of how to define a bean with initialization and destruction methods using annotations in Spring:

                
    import javax.annotation.PostConstruct;
    import javax.annotation.PreDestroy;
    import org.springframework.stereotype.Component;

    @Component
    public class MyBean {

        @PostConstruct
        public void init() {
            // initialization code here
        }

        public void doSomething() {
            // method implementation here
        }

        @PreDestroy
        public void cleanup() {
            // cleanup code here
        }
    }
                
            

In this example, MyBean defines an @PostConstruct method called init() that will be invoked after the bean has been instantiated and all dependencies have been injected. The bean also defines a @PreDestroy method called cleanup() that will be invoked before the bean is removed from the application context.

By using lifecycle methods, We can perform initialization and cleanup tasks for your beans, such as setting up database connections or closing resources when they're no longer needed.