當一個 bean 被實例化時,它可能須要執行一些初始化使它轉換成可用狀態。當bean再也不須要,而且從容器中移除時,須要作一些清除工做。爲了定義安裝和拆卸一個 bean,咱們只要聲明init-method 和/或 destroy-method 參數。init-method 屬性指定一個方法,在實例化 bean 時,當即調用該方法。一樣,destroy-method 指定一個方法,只有從容器中移除 bean 以後,才能調用該方法。java
編寫HelloWorld.javaspring
1 package com.example.spring; 2 3 public class HelloWorld { 4 private String message; 5 public void setMessage(String message){ 6 this.message = message; 7 } 8 9 public void getMessage(){ 10 System.out.println("Your Message : " + message); 11 } 12 //定義初始化方法 13 public void init(){ 14 System.out.println("Bean is going through init."); 15 } 16 //定義銷燬方法 17 public void destroy(){ 18 System.out.println("Bean will destroy now."); 19 } 20 }
編寫Beans.xml框架
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> 5 6 <bean id="helloWorld" 7 class="com.example.spring.HelloWorld" 8 init-method="init" destroy-method="destroy"> 9 <property name="message" value="Hello World"></property> 10 </bean> 11 </beans>
編寫Application.javathis
1 package com.example.spring; 2 3 import org.springframework.context.support.AbstractApplicationContext; 4 import org.springframework.context.support.ClassPathXmlApplicationContext; 5 6 public class Application { 7 public static void main(String[] args) { 8 //bean配置文件所在位置 D:\\IdeaProjects\\spring\\src\\Beans.xml 9 //使用AbstractApplicationContext容器 10 AbstractApplicationContext context = new ClassPathXmlApplicationContext("file:D:\\IdeaProjects\\spring\\src\\Beans.xml"); 11 HelloWorld obj = (HelloWorld)context.getBean("helloWorld"); 12 obj.getMessage(); 13 //registerShutdownHook關閉hook,確保正常關閉,並調用destroy方法 14 context.registerShutdownHook(); 15 } 16 }
運行輸出spa
Bean is going through init. Your Message : Hello World! Bean will destroy now.
默認的初始化和銷燬方法code
若是你有太多具備相同名稱的初始化或者銷燬方法的 Bean,那麼你不須要在每個 bean 上聲明初始化方法和銷燬方法。框架使用 元素中的 default-init-method 和 default-destroy-method 屬性提供了靈活地配置這種狀況,以下所示:xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" default-init-method="init" default-destroy-method="destroy"> <bean id="helloWorld" class="com.example.spring.HelloWorld"> <property name="message" value="Hello World"></property> </bean> </beans>
運行輸出blog
Bean is going through init.
Your Message : Hello World!
Bean will destroy now.