Spring provides call back methods for the life cycle of the beans. We can have a method in our bean that gets run when the bean is created and we can have a method which will run when the bean is about destroy. Hence we can use this methods for some initialization activity and for clean up activity as well .
We know how to configure lifecycle callbacks using configuration xml file. Here lets find out how to configure the same without using the configuration xml file.
Below is the Bean class which has two methods
init() and cleanUp ().
1 2 3 4 5 6 7 8 |
public class MyClass { public void init(){ System.out.println("Inside init"); } public void cleanUp(){ System.out.println("Inside cleanUp"); } } |
Lets create a class to configure the bean and its callback methods. initMethod is the attribute to configure the initialization method and destroyMethod is the attribute to configure the destroy method.
1 2 3 4 5 6 7 8 9 10 11 12 |
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class mySpringConf { @Bean(initMethod = "init", destroyMethod = "cleanUp" ) public MyClass myClass() { return new MyClass(); } } |
Below class SpringConfDemo is to test the initMethod and destryMethod configuration.
1 2 3 4 5 6 7 8 |
import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class SpringConfDemo { public static void main(String[] args) { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(mySpringConf.class); ctx.close(); } } |
Output:
Jun 06, 2017 1:45:42 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@2c634b: startup date [Tue Jun 06 13:45:42 IST 2017]; root of context hierarchy
Inside init
Jun 06, 2017 1:45:42 PM org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
INFO: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@2c634b: startup date [Tue Jun 06 13:45:42 IST 2017]; root of context hierarchy
Inside cleanUp
Here you can notice that:
- init method of the bean is getting called as soon as we create the context
- destroy method is getting called when we close the context.
Leave a Reply