Registering init and destroy methods using @Bean annotation

In this post under Spring Core, I will explain with example how to register initialization and destroy methods for a bean.

FYI, a bean initialization method is called when the bean is created and destroy method is called before bean is garbage collected.

All we need to tell Spring is which are the initialization and destroy methods in a bean.

Once Spring is informed, the framework will take care of calling these methods at appropriate time.

These methods should be present in the bean.

So for example if we have a bean say “Bean1”. It should have the below class structure

Bean1

1  package package5;
2  
3  public class Bean1 {
4      public void init() {
5          System.out.println("Started");
6      }
7      
8      public void close() {
9          System.out.println("Shutdown");
10     }
11     
12     @Override
13     public String toString() {
14         return "Hello its Bean1";
15     }
16 }

In the above code, we have “init” and “close” method.

Now we register those methods as initialization and destroy method of the bean as shown below

Main class

1 package package5;
2 
3 import org.springframework.context.annotation.AnnotationConfigApplicationContext;
4 import org.springframework.context.annotation.Bean;
5 import org.springframework.context.support.AbstractApplicationContext;
6 
7 @Configuration
8 public class Example5 {
9     @Bean(initMethod = "init", destroyMethod = "close")
10    public Bean1 bean1() {
11        return new Bean1();
12    }
13    
14    public static void main(String[] args) {
15        AbstractApplicationContext abstractApplicationContext = new AnnotationConfigApplicationContext(Example5.class);
16        Bean1 bean = abstractApplicationContext.getBean("bean1", Bean1.class);
17        System.out.println(bean);
18        abstractApplicationContext.close();
19    }
20}

The main class “Example5” is annotated with “@Configuration” annotation, which indicates Spring that this class contains bean definition.

In the “Example5” class at line 10 we have added a method of name “bean1”;

We annotated the method with @Bean annotation.

We also set the “initMethod” and “destroyMethod” attributes of “@Bean” annotation.

The values of “initMethod” is a method name from “Bean1” class and the value of “destroyMethod” attribute is a method name from “Bean1”.

In this way we are telling the Spring, that “Bean1” class has initialization and destroy method both.

In this way we have to register the initialization and destroy methods of a bean.

Below is the output

Output

Started
Hello its Bean1
Shutdown

Leave a Reply