为什么destroy-method在Spring MVC中出错?

时间:2011-09-09 07:23:57

标签: spring

我在我的bean中有破坏方法,但它没有在输出中显示。你能帮帮我吗?

package com.vaannila;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class HelloWorldApp {

    public static void main(String[] args) {
        AbstractApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Ticket helloWorld = (Ticket) context.getBean("ticket");
        helloWorld.setTicketNo("ABC009");
        helloWorld.display();
        context.close();
    }

}

下面是我的xml文件

<?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 id="helloWorld" class="com.vaannila.HelloWorld">
    <property name="message" value="Hello World!"></property>
</bean>

<bean id="ticket" class="com.vaannila.Ticket" 
scope="prototype" init-method="init" destroy-method="destroy"/>
</beans>

和Ticket类位于

之下
package com.vaannila;

public class Ticket {
private String ticketNo="";

public String getTicketNo() {
    return ticketNo;
}

public void setTicketNo(String ticketNo) {
    this.ticketNo = ticketNo;
}

public void display()
{
System.out.println("Your Ticket No. is"+ ticketNo);
}

public void init()
{
    System.out.println("Bean is ready You can use it now");
}
public void destroy()
{
   System.out.println("Bean is going to destroy");
}
}

输出为init方法但不包括destroy方法。 如果我将init-method和destroy-method更改为默认值,如下所示,它会在销毁名为“helloWorld”的bean时出错

 <?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"
     default-init-method="init" default-destroy-method="destroy">

<bean id="helloWorld" class="com.vaannila.HelloWorld">
    <property name="message" value="Hello World!"></property>
</bean>

<bean id="ticket" class="com.vaannila.Ticket" 
scope="prototype"/>



</beans>

1 个答案:

答案 0 :(得分:0)

当bean被定义为原型时,bean容器会在被要求提供该bean时创建新的实例。这就是原型范围内的豆子背后的想法。

创建它们之后,容器放弃了bean的责任。它无法知道您是否仍然保留对它的引用,或者您何时删除最后一个引用。即使在容器关闭后也是如此。 (容器不是垃圾收集器。)所以它不可能知道什么时候才能调用destroy方法。

如果你需要对你的机票进行取消初始化,你必须直接从你的代码中调用这样的方法我认为(假设使用单件票是没有意义的)。