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 略
}
<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)。