2011-09-09 43 views
0

我在我的bean中有銷燬方法,但它沒有顯示在輸出中。你能幫我在這裏嗎?爲什麼destroy-method在Spring MVC中發生錯誤?

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> 

和票務類低於

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方法而不是破壞方法.. 如果我改變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> 
+0

現在我才知道,如果bean在bean定義中具有prototype屬性,那麼destroy方法不會調用。但爲什麼有人能向我解釋? –

回答

0

當一個bean被定義爲原型時,每當bean容器被要求時,bean容器就會創建新的實例。這就是原型範圍的bean背後的想法。

創建它們後,容器放棄了bean的責任。它不知道你是否仍然持有對它的引用,或者你什麼時候放棄了最後的引用。即使在容器關閉後也是如此。 (容器不是垃圾收集器。)所以它不可能知道什麼時候調用destroy方法。

如果您需要爲您的票證進行初始化,您將不得不直接從您的代碼中調用此方法,我認爲(假設單身人士票證沒有意義)。

相關問題