1. 程式人生 > >spring的init-method 和 destory-method

spring的init-method 和 destory-method

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

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

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

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

直接上xml中配置檔案:

  1. <beanid="personService"class="com.myapp.core.beanscope.PersonService"scope="singleton"init-method="init"destroy-method="cleanUp">
  2. </bean
    >
定義PersonService類:
  1. package com.myapp.core.beanscope;  
  2. publicclass PersonService  {  
  3.    private String  message;  
  4.     public String getMessage() {  
  5.         return message;  
  6.     }  
  7.     publicvoid setMessage(String message) {  
  8.         this.message = message;  
  9.     }  
  10.     publicvoid init(){  
  11.         System.out.println("init");  
  12.     }  
  13.     //  how  validate the  destory method is  a question
  14.     publicvoid  cleanUp(){  
  15.         System.out.println("cleanUp");  
  16.     }  
  17. }  

相應的測試類:
  1. package com.myapp.core.beanscope;  
  2. import org.springframework.context.support.AbstractApplicationContext;  
  3. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  4. publicclass MainTest {  
  5.   publicstaticvoid main(String[] args) {  
  6.       AbstractApplicationContext  context =new  ClassPathXmlApplicationContext("SpringBeans.xml");  
  7.     PersonService  person = (PersonService)context.getBean("personService");  
  8.     person.setMessage("hello  spring");  
  9.     PersonService  person_new = (PersonService)context.getBean("personService");  
  10.     System.out.println(person.getMessage());  
  11.     System.out.println(person_new.getMessage());  
  12.     context.registerShutdownHook();  
  13. }  
  14. }   

測試結果:

init
hello  spring
hello  spring
cleanUp

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

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