只有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();//关闭容器 } }
//Service.java
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>
结果如图:
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-28 04:09:26