首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Spring Bean 生命週期(二):實作 InitializingBean / DisposableBean 介面

     編輯:Java 相關知識

回調介面

  • InitializingBean:void afterPropertiesSet() throws Exception — 屬性注入後調用。
  • DisposableBean:void destroy() throws Exception — 容器關閉前調用。

缺點:強耦合 Spring API,不推薦常規使用。

實作範例

public class Animal implements InitializingBean, DisposableBean { private String name; private int age; public void afterPropertiesSet() { System.out.println("afterPropertiesSet() 初始化"); } public void destroy() { System.out.println("destroy() 銷毀"); } public String speak() { return "名字:" + name + ",年齡:" + age; } // getter/setter 略 }

XML 配置(無需額外屬性)

<bean id="animal" class="ioc.test.Animal"> <property name="age" value="5"/> <property name="name" value="豬"/> </bean>

測試與結果

AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); ctx.registerShutdownHook(); Animal a = (Animal) ctx.getBean("animal"); System.out.println(a.speak());
afterPropertiesSet() 初始化
名字:豬,年齡:5
destroy() 銷毀

結語

雖可行但耦合 Spring,建議改用 init-method/destroy-method 或 @PostConstruct/@PreDestroy(JSR-250)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved