只有bean的生命周期为singleton且在程序末尾关闭容器时才会执行destroy-method方法
//ServiceTest.java
package com.mnmlist.initDestroy; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class ServiceTest { public static void main(String args[]) { ApplicationContext ctx=new ClassPathXmlApplicationContext("InitDestroy.xml"); Service service=(Service)ctx.getBean("service"); service.consumeService(); ((ClassPathXmlApplicationContext)ctx).close();//关闭容器 } }
package com.mnmlist.initDestroy; public class Service { public void arrangeTable() { System.out.println("I'm arranging the table!"); } public void cleanTable() { System.out.println("I have clean the table!"); } public void consumeService() { System.out.println("I'm consume the service!"); } }
<?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-3.0.xsd"> <bean id="service" class="com.mnmlist.initDestroy.Service" scope="singleton"//单例模式 destroy-method="cleanTable" init-method="arrangeTable" /> </beans>