PostConstruct and PreDestroy annotation
The `@PostConstruct` and `@PreDestroy` annotations are used in Spring to manage the lifecycle of beans. They allow you to specify methods that should be executed after a bean has been initialized and before it is destroyed, respectively.
Table of Contents
`@PostConstruct`:
This annotation is used to mark a method that should be executed after the bean’s properties have been set and the bean is fully initialized. It is often used to perform initialization tasks or setup actions.
`@PreDestroy`:
This annotation is used to mark a method that should be executed just before the bean is destroyed. It is typically used for cleanup tasks, such as releasing resources or closing connections.
Example
- Step 1: Create a Spring Boot Application
- Ensure you have the necessary dependencies in your `pom.xml` (for Maven) or `build.gradle` (for Gradle).
Maven Dependency
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
```
Gradle Dependency
```groovy
implementation 'org.springframework.boot:spring-boot-starter'
```
- Step 2: Create the Main Application Class
- Create the main class for the Spring Boot application.
Example
```java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
```
Explanation:
- `@SpringBootApplication`: Indicates a configuration class that declares one or more `@Bean` methods and also triggers auto-configuration and component scanning.
- Step 3: Create a Bean with `@PostConstruct` and `@PreDestroy` Methods
- Define a Spring bean that uses `@PostConstruct` and `@PreDestroy` annotations.
Example
```java
package com.example.demo.service;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.springframework.stereotype.Service;
@Service
public class MyService {
@PostConstruct
public void init() {
// Initialization logic
System.out.println("MyService bean has been initialized.");
}
@PreDestroy
public void cleanup() {
// Cleanup logic
System.out.println("MyService bean is about to be destroyed.");
}
}
```
Explanation:
- `@PostConstruct`: The `init` method will be called after the `MyService` bean is fully initialized.
- `@PreDestroy`: The `cleanup` method will be called before the `MyService` bean is destroyed.
- Step 4: Create a Controller to Use the Service
- Create a REST controller to expose some endpoints.
Example
```java
package com.example.demo.controller;
import com.example.demo.service.MyService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class ApiController {
private final MyService myService;
public ApiController(MyService myService) {
this.myService = myService;
}
@GetMapping("/hello")
public String hello() {
return "Hello from MyService!";
}
}
```
Explanation:
- `@RestController`: Indicates that this class is a REST controller and its methods return data directly to the HTTP response body.
- `@RequestMapping(“/api”)`: Maps the URL `/api` to the `ApiController` methods.
- `@GetMapping(“/hello”)`: Maps HTTP GET requests to the `hello` method, which returns a simple greeting.
- Step 5: Running the Application
- Run the application from the main class (`DemoApplication`). Access the `/api/hello` endpoint to verify the service is operational.
- Step 6: Observing the Lifecycle Methods
- Monitor the console logs to see the output from `@PostConstruct` and `@PreDestroy` methods. You should see:
- “MyService bean has been initialized.” when the application starts.
- “MyService bean is about to be destroyed.” when the application is stopped or the bean is removed.
Conclusion:
- `@PostConstruct`: Used for initialization logic that needs to be executed after bean creation.
- `@PreDestroy`: Used for cleanup logic that needs to be executed before the bean is destroyed.
- Example: Demonstrated how to use these annotations to manage bean lifecycle events in a Spring Boot application.