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 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名