在Web应用程序中注册shutDownHook

sli*_*hyi 23 java spring tomcat ioc-container web

我们如何在Web应用程序中注册关闭挂钩?

有没有什么可以在web.xml或applicationContext.xml中注册它?

我知道如果我们使用主类的应用程序,那很简单.

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
    context.registerShutdownHook();
Run Code Online (Sandbox Code Playgroud)

但是Web应用程序怎么样?因为它使用ContextListener

Kal*_*yan 21

独立(非Web)应用程序中的registerShutdownHook():

@PreDestroy上豆方法用于注释当豆被从上下文移除或当所述上下文被关闭时得到通知.

在调用context.close()context.registerShutdownHook()调用时触发关闭事件.

@Component(value="someBean")
public class SomeBean {

    @PreDestroy
    public void destroy() {
        System.out.println("Im inside destroy...");
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望你已经知道了.


web应用程序中的registerShutdownHook():

在Web应用程序中,DispatcherServlet/ContextListener创建ApplicationContext,它将在服务器关闭时关闭上下文.你并不需要显式调用context.close()context.registerShutdownHook().

当服务器关闭时,@PreDestory将自动通知bean上的方法.

  • @Kalyan :: @ Predestroy被称为Bean销毁,这意味着如果bean不是单例,只要容器移除bean,就会多次调用它. (2认同)

Lui*_*oza 5

在Web应用程序中,可以使用ServletContextListener部署和取消部署应用程序时触发的:

public class MyServletContextListener implements ServletContextListener {
    public void contextInitialized(ServletContextEvent sce) {
        //application is being deployed
    }
    public void contextDestroyed(ServletContextEvent sce) {
        //application is being undeployed
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以通过获取当前的Spring上下文来访问Spring Bean:

public void contextDestroyed(ServletContextEvent sce) {
    ServletContext ctx = sce.getServletContext();
    WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(ctx);
    //retrieve your Spring beans here...
    SomeSpringBean bean = (SomeSpringBean)ctx.getBean("someSprinbgBean");
    //...
}
Run Code Online (Sandbox Code Playgroud)