Spring Bean Life Cycle - @Bean’s initMethod and destroyMethod attributes example

Posted on January 21, 2017


Technologies used:   JDK 1.8.0_121 | Spring 4.3.5.RELEASE | Maven 3.3.9 | Eclipse Mars.2 (4.5.2)

In our previous post, we have learned the Spring Bean Life Cycle - @PostConstruct and @PreDestroy example.

In this post, we will show you how to use initMethod and destroyMethod attributes of the @Bean annotation to perform certain actions after bean initialization or before bean destruction by container.

Consider the following MailService bean.

MailService.java

package com.boraji.tutorial.spring;

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

/**
 * @author imssbora
 */
public class MailService {

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

   public void send(String mailTo){
      //Send mail code
      System.out.println("Inside send method - "+mailTo);
   }
   
   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);
   }

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

Declare the MailService in AppConfig class as follows.

AppConfig.java

package com.boraji.tutorial.spring;

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

/**
 * @author imssbora
 */
@Configuration
public class AppConfig {
   @Bean(initMethod="init",destroyMethod="destroy")
   public MailService getMailService() {
      return new MailService();
   }
}

Create main class and run application.

MainApp.java

package com.boraji.tutorial.spring;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

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

      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 - {}