Spring Bean Life Cycle - @PostConstruct and @PreDestroy

Spring Bean Life Cycle - @PostConstruct and @PreDestroy

In Spring framework, we can manage lifecycle of a bean by using method-level annotations?@PostConstruct?and?@PreDestroy.

The?@PostConstruct?annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization.

The?@PreDestroy?annotation is used on methods as a callback notification to signal that the instance is in the process of being removed by the container.

The following examples demonstrate the use of?@PostConstruct?and?@PreDestroy?annotations.

Consider the?MailService?bean, whose?init()?and?destroy()?methods are annotated with?@PostConstruct?and?@PreDestroy?annotations respectively.

MailService.java

import java.util.HashMap
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.springframework.stereotype.Component;

/**
 * @author anjum
 */
@Component
public class MailService {

   private Map<String, String> map=null;
   
   public MailService() {
      map=new HashMap<>();
   }

   public void send(String mailTo){
      //Code for sending mail
      System.out.println("Inside send method - "+mailTo);
   }
   
   @PostConstruct
   public void init() {
      map.put("host", "mail.example.com");
      map.put("port", "25");
      map.put("from", "[email protected]");
      System.out.println("Inside init method - "+map);
   }

   @PreDestroy
   public void destroy() {
      map.clear();
      System.out.println("Inside destroy method - "+map);
   }
};        

Create?AppConfig?class and write the following code in it.

App.Config.java

package com.boraji.tutorial.spring

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
 * @author anjum
 */
@Configuration
@ComponentScan(basePackages = "com.anjum.tutorial.spring")
public class AppConfig {
   
};        

Note -?@ComponentScan?annotation scans all beans, whose class is annotated by the?@Component?annotation in a package, specified by?basePackages?attribute.

Create main class and run application.

MainApp.java

import org.springframework.context.annotation.AnnotationConfigApplicationContext

/**
 * @author anjum
 */
public class MainApp {
   public static void main(String[] args) {
      AnnotationConfigApplicationContext context = 
            new AnnotationConfigApplicationContext(AppConfig.class);
      
      // Send mail 1
      MailService mailService1 = context.getBean(MailService.class);
      mailService1.send("[email protected]");

      // Send mail 2
      MailService mailService2 = context.getBean(MailService.class);
      mailService2.send("[email protected]");

      context.close();
   }
};        

Output

Inside init method - {port=25, host=mail.example.com, [email protected]}
Inside send method - [email protected]
Inside send method - [email protected]
Inside destroy method - {}        

As you can see, the?init()?and?destroy()?methods of?MailService?bean are called only once, when the scope of bean is singleton (default scope).

In case of prototype scope, the destroy method of the?MailService?bean will not work. You can try this by downloading the sources from the below download link.

Jayakumar Chilakalapudi

Java Developer | Spring Boot | Microservices | AWS | Docker | Overall Experience 2 years

1 年

thank you!

要查看或添加评论,请登录

Abid Anjum的更多文章

  • Challenges in Developing Spring Boot Microservices with Spring Cloud

    Challenges in Developing Spring Boot Microservices with Spring Cloud

    Spring Boot has revolutionized the way developers build applications, particularly when it comes to microservices…

  • Microservice Challenges and Solutions

    Microservice Challenges and Solutions

    1: Microservice Dependency Failure One microservice crucial for the application’s functionality is frequently…

  • NGINX Plus

    NGINX Plus

    NGINX Plus and NGINX are the best-in-class reverse proxy and load balancing solutions used by high-traffic websites…

  • INTRODUCTION

    INTRODUCTION

    We are going to look at the features and benefits of using a Kubernetes cluster to deploy your application…

  • Clean Architecture

    Clean Architecture

    Clean architecture is a domain-centric architectural pattern that separates the business logic into two layers…

  • How to Deploy Microservices Using Serverless Architecture?

    How to Deploy Microservices Using Serverless Architecture?

    Monoliths vs. Microservices Whereas monolithic applications are built and deployed as one holistic unit…

  • Ways to Visualize Geospatial Data in a Web Browser

    Ways to Visualize Geospatial Data in a Web Browser

    Choosing a Web Visualization Library Step one. Here are a few questions to ask yourself: What kind of data do you need…

  • Java Collections Framework & Time Complexity Of Operations

    Java Collections Framework & Time Complexity Of Operations

    1. ArrayList It is used for fast random access and is mainly for storing and accessing data sequentially.

  • Improve API Performance

    Improve API Performance

    1. Caching: Leverage caching mechanisms to store frequently requested data, reducing the load on your backend and…

  • Monoliths vs Microservices

    Monoliths vs Microservices

    Monoliths vs Microservices a side by side comparison Deployability Scalability Communication Databases

社区洞察