Skip to main content

[Writing Practice]: Bean Life Cycle in Java Spring

· 3 min read
Link Nuis
Java Developer
warning

This blogs solely for writing practice, so it's primarily a copy blog/article, not intended for content dissemination.

Root blog/article: bean-life-cycle

The Spring Bean Life Cycle describes the sequence of steps a bean goes through from its creation to destruction within the Spring IoC (Inversion of Control) container.

Phases of Spring Bean Life Cycle​

A Spring bean typically passes through the following phases:

  • Container Initialization: The Spring IoC container is started.

  • Bean Instantition: The container creates an instance of the bean.

  • Dependency Injection: Dependencies are injected using constructor, setter, or field injection.

  • Initialization Callback: Custom initialization logic is executed.

  • Bean Ready for Use: The bean is fully initialized and available for use

  • Container Shutdown: The Spring container is closed.

  • Destruction Callback: Cleanup logic is executed before bean destruction.

note

Custom method names can be used instead of default lifecycle method names.

Implement Bean Life Cycle in Spring​

There is many way to implement Bean Life Cycle, such as:

  • XML Configuration
  • Programmatic Approach (Interfaces)
  • Annotations

But in this blog, we just focus on implement using Annotations.

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

  • @PostConstruct -> called after the bean is created and dependencies are injected.
  • @PreDestroy -> called just before the bean is destroyed.
info

To invoke the destroy() method, we have to call the close() method of ConfigurableApplicationContext.

Step 1: Create project​

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

Step 2: Add Required Dependencies​

pom.xml
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.30</version>
</dependency>

<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>

Step 3: Create the Bean Class​

Create a simple bean class and use lifecycle annotations.

HelloWorld.java
package beans;
import javax.annotation.PostConstruct;
import javax.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");
}
}

Explaintation​

  • @PostConstruct runs after the bean is instantiated and dependencies are injected.
  • @PreDestroy runs just before the bean is destroyed.

Step 4: Enable Annotation Support (XML)​

Enable annotation processing in the Spring XML file.

spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">

<context:annotation-config/>

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

</beans>

Explaination​

  • CommonAnnotationBeanPostProcessor is enabled internally.
  • Actiavates @PostConstruct and @PreDestroy annotations.

Step 5: Create the Driver Class​

Create a class to load and close the Spring container.

Client.java
package test;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Client {
public static void main(String[] args) throws InterruptedException {
ConfigurableApplicationContext context =
new ClassPathXmlApplicationContext("spring.xml");
//close container
// if you don't, @PostConstruct will not executed even if application shut down
context.close();

System.out.println("do something else...");
Thread.sleep(1000);
}
}

See result after run​

bean-life-cycle.png