在Web应用程序中注册shutDownHook

 绝非韩版560 发布于 2023-01-12 16:22

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

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

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

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
    context.registerShutdownHook();

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

2 个回答
  • 在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
        }
    }
    

    您可以通过获取当前的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");
        //...
    }
    

    2023-01-12 16:24 回答
  • 独立(非Web)应用程序中的registerShutdownHook():

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

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

    @Component(value="someBean")
    public class SomeBean {
    
        @PreDestroy
        public void destroy() {
            System.out.println("Im inside destroy...");
        }
    }
    

    我希望你已经知道了.


    web应用程序中的registerShutdownHook():

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

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

    2023-01-12 16:24 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有