Bean Life Cycle in Java Spring (original) (raw)

The Spring Bean Life Cycle describes the internal workflow followed by the Spring IoC container to manage a bean, start from object instantiation through dependency injection and initialization and ending with destruction.

Spring Bean Life Cycle

A Spring bean goes through the following phases inside the IoC container

container_started

Spring Bean Life Cycle

Container Initialization

Bean Instantiation

Dependency Injection

Custom Init Method

Custom Utility Method

Destruction

**Note: Custom method names can be used instead of default lifecycle method names.

Ways to Implement Bean Life Cycle in Spring

Spring provides three standard ways to manage the bean life cycle:

  1. XML Configuration
  2. Programmatic Approach (Interfaces)
  3. Annotations

1. Using XML Configuration

In this approach, in order to avail custom init() and destroy() methods for a bean we have to register these two methods inside the Spring XML configuration file while defining a bean. Therefore, the following steps are followed:

Step 1: Create the Project

Step 2: Project Structure

Organize the project using standard Maven directories for Java source files and resource files.

XML_Str

Project Structure

Step 3: Add Spring Dependency

Open pom.xml and add:

XML `

org.springframework spring-context 5.3.30

`

Step 4: Create the Bean Class

Create a simple Spring bean with custom init() and destroy() methods to handle initialization and destruction logic.

**HelloWorld.java

Java `

package beans; public class HelloWorld { public void init() { System.out.println("Bean initialized using XML"); } public void destroy() { System.out.println("Bean destroyed using XML"); } }

`

**Explanation:

Step 5: Configure the Spring XML

Define the bean in the Spring XML file and register the init-method and destroy-method.

**spring.xml

Java `

<!-- Bean definition with custom init and destroy methods -->
<bean id="hw" class="beans.HelloWorld"
      init-method="init"
      destroy-method="destroy"/>

`

**Explanation:

Step 6: Create Driver Class

We need to create a driver class to run this bean.

Java `

package test; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Client {

public static void main(String[] args) {
    ConfigurableApplicationContext context =
        new ClassPathXmlApplicationContext("spring.xml");
    context.close();
}

}

`

**Explanation:

Step 7: Run the Application

Run the driver class to observe the execution of the bean’s initialization and destruction methods.

**Output:

xml_output

Output

2. Using Programmatic Approach (Interface)

In this approach, a Spring bean can define custom initialization and destruction logic by implementing two Spring-provided interfaces: **InitializingBean and **DisposableBean.

**Note: To trigger the destroy() method, we must explicitly close the Spring container using ConfigurableApplicationContext.close().

Step 1: Create the Project

Create a Maven project in IntelliJ IDEA with the required GroupId, ArtifactId, and Java version.

Step 2: Project Structure

Arrange the project into standard Maven folders for Java source files and resource files.

pro_stru

Project Structure

Step 3: Add Spring Dependency (pom.xml)

Add the spring-context dependency in pom.xml to enable Spring core and lifecycle support.

XML `

org.springframework spring-context 5.3.30

`

Step 4: Create the Bean Class

Implement InitializingBean and DisposableBean in the bean class to define custom initialization and destruction logic.

**HelloWorld.java

Java `

package beans; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; public class HelloWorld implements InitializingBean, DisposableBean { @Override public void afterPropertiesSet() throws Exception { System.out.println( "Bean HelloWorld has been instantiated and I'm the init() method" ); }

@Override
public void destroy() throws Exception {
    System.out.println(
        "Container has been closed and I'm the destroy() method"
    );
}

}

`

**Explanation:

Step 5: Configure the Spring XML File

Define the bean in spring.xml so that Spring can manage its lifecycle.

**spring.xml

XML `

<bean id="hw" class="beans.HelloWorld"/>

`

**Explanation:

Step 6: Create the Driver Class

Load the Spring container using ClassPathXmlApplicationContext to initialize the bean. Close the ConfigurableApplicationContext to trigger the destroy() lifecycle method.

**Client.java

Java `

package test; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Client {

public static void main(String[] args) throws Exception {

    ConfigurableApplicationContext context =
        new ClassPathXmlApplicationContext("spring.xml");

    context.close();
}

}

`

**Explanation:

Step 7: Run the Application

Run the driver class to observe the execution of initialization and destruction methods.

**Output:

pro_output

Output

**Note: This approach tightly couples the bean with Spring APIs, so it is not recommended for modern applications.

3. Using Annotations

In this approach, Spring provides lifecycle management using annotations instead of interfaces or XML configuration.

**Note: To invoke the destroy() method we have to call the close() method of ConfigurableApplicationContext.

Step 1: Create the Project

  1. Open IntelliJ IDEA
  2. Click New Project -> Maven
  3. Select JDK (Java 8 / 11 / 17)
  4. Enter: GroupId: beans, ArtifactId: SpringAnnotationLifecycleDemo
  5. Click Finish

Step 2: Project Structure

stu

Project Structure

Step 3: Add Required Dependencies

XML `

org.springframework spring-context 6.1.0 jakarta.annotation jakarta.annotation-api 2.1.1

`

Step 4: Create the Bean Class

Create a simple bean class and use lifecycle annotations.

**HelloWorld.java

Java `

package beans;

import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy;

public class HelloWorld {

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

@PreDestroy
public void destroy() {
    System.out.println("Bean destroyed using annotations");
}

}

`

**Explanation:

Step 5: Enable Annotation Support (XML)

Enable annotation processing in the Spring XML file.

**spring.xml

XML `

<context:annotation-config/>

<bean id="hw" class="beans.HelloWorld"/>

`

**Explanation:

Step 6: Create the Driver Class

Create a class to load and close the Spring container.

**Client.java

Java `

package test; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Client { public static void main(String[] args) { ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");

    context.close();
}

}

`

Step 7: Run the Application

**Output:

output

Output

**Note: