Anhe0901 2017-10-23 07:52 采纳率: 66.7%
浏览 3800
已采纳

Spring的destroy方法不执行

Spring可以通过配置init-method和destroy-method属性来在容器生成和销毁时分别执行一段代码,但在我的demo中,作为init方法的start方法执行了,而作为destroy方法的shutdown方法一直没有执行,代码如下:
配置文件:

 <?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.xsd">

    <bean class="com.ljh.beans.Foo2" id="foo2" scope="prototype" init-method="start" destroy-method="shutdown">
        <property name="foo" ref="foo"></property>
    </bean>

    <bean class="com.ljh.beans.Foo" id="foo" scope="prototype">
        <property name="num" value="2"></property>
    </bean>
</beans>

Bean文件:

 public class Foo2 {

    private Foo foo;

    public void say(){
        System.out.println("Foo2 method:" + foo.hashCode());
        System.out.println("Foo2 hashcode" + this.hashCode());
        System.out.println("----------------------");
    }

    private void start() {
        System.out.println("Start method");
    }

    private void shutdown() {
        System.out.println("Shutdown method");
    }

    public Foo getFoo() {
        return foo;
    }

    public void setFoo(Foo foo) {
        this.foo = foo;
    }

}

测试方法:

 public class Test01 {

    private ApplicationContext context;

    @Before
    public void init() {
        context = new ClassPathXmlApplicationContext("/springConfig.xml");
    }

    @Test
    public void Test() {
        Foo2 foo2 = (Foo2) context.getBean("foo2");
        System.out.println(foo2.getFoo().getNum());
    }

    @After
    public void After() {
        System.out.println("In after method");
        ((ClassPathXmlApplicationContext) context).close();
    }
  • 写回答

1条回答 默认 最新

  • 凡恩 2017-12-02 14:29
    关注

    当使用 init-method 和 destroy-method 的时候,使用 prototype 时 Spring 不会负责销毁容器对象,即 Spring 不会调用 destroy-method 所指定的方法,所以需要去掉 scope 属性,使用默认的 singleton

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 cgictest.cgi文件无法访问
  • ¥20 删除和修改功能无法调用
  • ¥15 kafka topic 所有分副本数修改
  • ¥15 小程序中fit格式等运动数据文件怎样实现可视化?(包含心率信息))
  • ¥15 如何利用mmdetection3d中的get_flops.py文件计算fcos3d方法的flops?
  • ¥40 串口调试助手打开串口后,keil5的代码就停止了
  • ¥15 电脑最近经常蓝屏,求大家看看哪的问题
  • ¥60 高价有偿求java辅导。工程量较大,价格你定,联系确定辅导后将采纳你的答案。希望能给出完整详细代码,并能解释回答我关于代码的疑问疑问,代码要求如下,联系我会发文档
  • ¥50 C++五子棋AI程序编写
  • ¥30 求安卓设备利用一个typeC接口,同时实现向pc一边投屏一边上传数据的解决方案。