2011-05-07 47 views

回答

14

如果你定义一个实现了DisposableBean接口的bean Spring会destrying豆前致电

void destroy() throws Exception; 

方法。

这是一种方式,另一种方式是当你的bean不必实现给定的接口。 在您的ConfigurationSupport类之一中,必须将bean定义为带有@Bean注释的pulic方法。

@Bean (destroyMethod="yourDestroyMethod") 
    public YourBean yourBean() { 
     YourBean yourBean = new YourBean(); 

     return yourBean; 
    } 

的方法“yourDestroyMethod”在YourBean.class加以界定和Spring会破坏bean之前调用它。

欲了解更多信息请参阅Spring文档:Destruction callbacks

UPDATE

第三条道路...... 我甚至会说,更好的办法将specifiy“初始化方法”和“破坏方法“......像这样:mkyong.com/spring/spring-init-method-and-destroy-method-example

这就解决了第三方依赖bean的问题,并且解放了不需要代码的Spring接口..

+0

我不知道,但我发现有@PostConstruct和@PreDestroy注释。请参阅:http://static.springsource.org/spring/docs/3.0.x/reference/beans.html#beans-postconstruct-and-predestroy-annotations – davorp 2011-05-09 08:48:18

+1

我发现@PostConstruct和@PreDestroy比其他更清晰做这种事的方法;它将魔法降至最低。 – 2011-05-09 09:17:57

+0

这就是我一直在寻找的!该文档讨论了DisposableBean和@PreDestroy,但我想知道如何为第三方类(如org.apache.commons.dbcp.BasicDataSource)指定此位置,以便无法触及其代码。非常感谢! – 2013-04-25 10:16:47

3

你的意思是像使用标准JDK @PreDestroy注释方法?这在Spring中很普遍,通常比使用XML中的bean声明的destroy-method属性更好。所有你需要做的是包括

<context:annotation-config/> 

在你的配置文件和Spring处理其余。

0

有标准的.NET IDisposable.Dispose()方法。我不知道春天,但从快速谷歌搜索似乎@predestroy几乎是相同的概念。

6

有3种方法可以做到这一点。如所陈述

@PreDestroy标签

在XML破坏法

DisposableBean的界面正上方

我faivorite是@PreDestroy方法。

要做到这一点u需要:

在应用程序的context.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" 
     xmlns:context="http://www.springframework.org/schema/context" 
     xsi:schemaLocation="http://www.springframework.org/schema/beans 
          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
          http://www.springframework.org/schema/context 
          http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 

    <bean id="shutDownBean" class="spring.ShutDownBean" /> 
    <context:annotation-config/> 
</beans> 

将使得@PreDestroy@PostDestroy标签可用。 现在让我们说你有ShutDownBean,你想在关闭回调被调用时运行一些代码。 注册该bean。

import javax.annotation.PreDestroy; 

public final class ShutDownBean { 

    @PreDestroy 
    public static void shutDownMethod() { 
     System.out.println("Shutting down!"); 
    } 

} 

现在你已经完成了。

如果你有桌面应用程序然后用你需要关闭它像这样的注解@PreDestroy:

AbstractApplicationContext applicationContext = 
       new ClassPathXmlApplicationContext("application-context.xml"); 
applicationContext.registerShutdownHook(); 

注: AbstractApplicationContextregisterShutdownHook(执行)所以这是您可以使用的最低等级。

此外,如果你可以使用销毁方法标签的类,你不控制它们的实现。例如,您可以将其添加到applcation-context.xml中:

<bean id = "dataSource" 
     class = "org.apache.commons.dbcp.BasicDataSrouce" 
     destroy-method = "close"> 

destroy-method值可以具有任何可见性,但不需要参数。

希望这会有所帮助!