在 <bean> 標籤指定:
<bean id="animal" class="ioc.test.Animal" init-method="start" destroy-method="end">
<property name="age" value="5"/>
<property name="name" value="豬"/>
</bean>
全域預設:<beans default-init-method="start" default-destroy-method="end">。
public class Animal {
private String name; private int age;
public void start() { System.out.println("初始化 start()"); }
public void end() { System.out.println("銷毀 end()"); }
public String speak() { return "名字:" + name + ",年齡:" + age; }
// getter/setter 略
}
AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
ctx.registerShutdownHook(); // 必須註冊關閉鉤子,才會觸發 destroy-method
Animal a = (Animal) ctx.getBean("animal");
System.out.println(a.speak());
初始化 start() 名字:豬,年齡:5 銷毀 end()

public void xxx() throws Exception。registerShutdownHook() 或手動 ctx.close() 才會調用銷毀回調。