Spring是否有关闭进程来放置清理代码?

时间:2011-12-21 05:14:57

标签: java spring

当我的春季网络应用程序关闭时,是否有一个事件我可以以某种方式连线,我可以执行一些清理代码以清空一些池等。

5 个答案:

答案 0 :(得分:30)

您可以使用以下

  1. destroy-method as @ amir75 recommended

  2. @PreDestroy注释

  3. 实施DisposableBean并覆盖销毁方法。

  4. 关于这些的所有deatails都可以在Disposable Callbacks找到。

答案 1 :(得分:6)

Spring bean有一个'destroy-method'属性,当你'关闭'你的上下文时会调用它。

<bean id="bean1" 
    destroy-method="stop"
    class="com.example.Bean" />

要关闭它,你可以调用close()方法:

http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/context/support/AbstractApplicationContext.html#close%28%29

(或者只是在适当的时候关闭容器)

希望有所帮助..

答案 2 :(得分:5)

基于JSR-250规范,在现代spring应用程序中使用的最佳实践是@PreDestroy注释,因为使用此方法将使bean与Spring分离。

答案 3 :(得分:4)

处理此问题的非Spring方法是编写一个实现ServletContextListener的类,并在其contextDestroyed方法中进行清理。您将在web.xml中将您的类添加为上下文侦听器。

答案 4 :(得分:2)

根据Spring Boot logback示例项目,您应关闭上下文以清理日志记录系统:https://github.com/spring-projects/spring-boot/commit/10402a651f1ee51704b58985c7ef33619df2c110

示例:

public static void main(String[] args) throws Exception {
        SpringApplication.run(SampleLogbackApplication.class, args).close();
    }