1. 程式人生 > 程式設計 >Spring實戰之Bean銷燬之前的行為操作示例

Spring實戰之Bean銷燬之前的行為操作示例

本文例項講述了Spring實戰之Bean銷燬之前的行為操作。分享給大家供大家參考,具體如下:

一 配置

<?xml version="1.0" encoding="GBK"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns="http://www.springframework.org/schema/beans"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
   <bean id="steelAxe" class="org.crazyit.app.service.impl.SteelAxe"/>
   <!-- 配置chinese Bean,使用destroy-method="close"
      指定該Bean例項被銷燬之前,Spring會自動執行指定該Bean的close方法 -->
   <bean id="chinese" class="org.crazyit.app.service.impl.Chinese"
      destroy-method="close">
      <property name="axe" ref="steelAxe"/>
   </bean>
</beans>

二 介面

1 Axe

package org.crazyit.app.service;
public interface Axe
{
   public String chop();
}

2 Person

package org.crazyit.app.service;
public interface Person
{
   public void useAxe();
}

三 Bean

1 Chinese

package org.crazyit.app.service.impl;
import org.springframework.beans.factory.DisposableBean;
import org.crazyit.app.service.*;
public class Chinese implements Person,DisposableBean
{
  private Axe axe;
  public Chinese()
  {
    System.out.println("Spring例項化主調bean:Chinese例項...");
  }
  public void setAxe(Axe axe)
  {
    System.out.println("Spring執行依賴關係注入...");
    this.axe = axe;
  }
  public void useAxe()
  {
    System.out.println(axe.chop());
  }
  public void close()
  {
    System.out.println("正在執行銷燬之前的方法 close...");
  }
  public void destroy() throws Exception
  {
    System.out.println("正在執行銷燬之前的方法 destroy...");
  }
}

2 SteelAxe

package org.crazyit.app.service.impl;
import org.crazyit.app.service.*;
public class SteelAxe implements Axe
{
   public SteelAxe()
   {
      System.out.println("Spring例項化依賴bean:SteelAxe例項...");
   }
   public String chop()
   {
      return "鋼斧砍柴真快";
   }
}

四 測試類

package lee;
import org.springframework.context.*;
import org.springframework.context.support.*;
import org.crazyit.app.service.*;
public class BeanTest
{
  public static void main(String[] args)
  {
    // 以CLASSPATH路徑下的配置檔案建立ApplicationContext
    AbstractApplicationContext ctx = new
      ClassPathXmlApplicationContext("beans.xml");
    // 獲取容器中的Bean例項
    Person p = ctx.getBean("chinese",Person.class);
    p.useAxe();
    // 為Spring容器註冊關閉鉤子
    ctx.registerShutdownHook();
  }
}

五 測試結果

Spring例項化依賴bean:SteelAxe例項...
Spring例項化主調bean:Chinese例項...
Spring執行依賴關係注入...
鋼斧砍柴真快
九月 21,2019 9:30:18 下午 org.springframework.context.support.ClassPathXmlApplicationContext doClose
資訊: Closing org.springframework.context.support.ClassPathXmlApplicationContext@5a10411: startup date [Sat Sep 21 21:30:18 CST 2019]; root of context hierarchy
正在執行銷燬之前的方法 destroy...
正在執行銷燬之前的方法 close...

更多關於java相關內容感興趣的讀者可檢視本站專題:《Spring框架入門與進階教程》、《Java資料結構與演算法教程》、《Java操作DOM節點技巧總結》、《Java檔案與目錄操作技巧彙總》和《Java快取操作技巧彙總》

希望本文所述對大家java程式設計有所幫助。