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上的方法.
在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)
| 归档时间: |
|
| 查看次数: |
24222 次 |
| 最近记录: |