Spring容器優雅的關閉

關於在spring  容器初始化 bean 和銷燬前所做的操作定義方式有三種:

第一種:通過@PostConstruct 和 @PreDestroy 方法 實現初始化和銷燬bean之前進行的操作

第二種是:通過 在xml中定義init-method 和  destory-method方法

第三種是: 通過bean實現InitializingBean和 DisposableBean接口



在xml中配置 init-method和 destory-method方法

只是定義spring 容器在初始化bean 和容器銷燬之前的所做的操作

基於xml的配置只是一種方式:


直接上xml中配置文件:

[html] view plain copy
  1. <bean id="personService" class="com.myapp.core.beanscope.PersonService" scope="singleton"  init-method="init"  destroy-method="cleanUp">  
  2.   
  3. </bean>  


定義PersonService類:

[java] view plain copy
  1. package com.myapp.core.beanscope;  
  2.   
  3.   
  4. public class PersonService  {  
  5.    private String  message;  
  6.   
  7.     public String getMessage() {  
  8.         return message;  
  9.     }  
  10.       
  11.     public void setMessage(String message) {  
  12.         this.message = message;  
  13.     }  
  14.      
  15.   
  16.       
  17.     public void init(){  
  18.         System.out.println("init");  
  19.     }  
  20.     //  how  validate the  destory method is  a question  
  21.     public void  cleanUp(){  
  22.         System.out.println("cleanUp");  
  23.     }  
  24. }  

相應的測試類:

[java] view plain copy
  1. package com.myapp.core.beanscope;  
  2.   
  3. import org.springframework.context.support.AbstractApplicationContext;  
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  5.   
  6. public class MainTest {  
  7.   public static void main(String[] args) {  
  8.         
  9.       AbstractApplicationContext  context =new  ClassPathXmlApplicationContext("SpringBeans.xml");  
  10.       
  11.     PersonService  person = (PersonService)context.getBean("personService");  
  12.       
  13.     person.setMessage("hello  spring");  
  14.       
  15.     PersonService  person_new = (PersonService)context.getBean("personService");  
  16.       
  17.     System.out.println(person.getMessage());  
  18.     System.out.println(person_new.getMessage());  
  19.     context.registerShutdownHook();  
  20.   
  21.       
  22. }  
  23. }   

測試結果:

init
hello  spring
hello  spring
cleanUp

可以看出 init 方法和 clean up方法都已經執行了。


context.registerShutdownHook(); 是一個鉤子方法,當jvm關閉退出的時候會調用這個鉤子方法,在設計模式之 模板模式中 通過在抽象類中定義這樣的鉤子方法由實現類進行實現,這裏的實現類是AbstractApplicationContext,這是spring 容器優雅關閉的方法。


原作者出處:http://blog.csdn.net/topwqp/article/details/8681467


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章