public void contextDestroyed(ServletContextEvent sce) {
System.out.println("===========关闭spider!===========");
stopSpider();
}
ServletContextListener 接口的contextDestroyed () 方法用于工程停止时释放资源,但使用eclipse集成的tomcat进行测试时,资源没有释放。
为了判断方法是否执行,我在方法里面添加了System.out,但控制台没有打印出“========关闭spider!=========”。
查资料发现通过eclipse关闭tomcat的时候,如果在console界面关闭,实际上是Terminate,而在Servers界面关闭是Stop,Stop可以正常在控制台打印出销毁信息,推测Terminate可能是直接关闭tomcat进程,所以还没有调用contextDestroyed()方法就结束了,所以看不到销毁信息。
之后我将工程部署到服务器测试,服务器停止时资源正常释放了,看日志有“========关闭spider!=========”输出;说明部署到服务之后,关闭服务器时contextDestroyed()方法会正常调用。
参考:https://blog.csdn.net/FreemanZhao/article/details/54918130?utm_source=blogxgwz1
https://blog.csdn.net/tempdowncomputer/article/details/84410989