【Java】ServletContextListener没有打印contextDestroyed方法内的日志问题
场景
@Slf4j public class ScanJob implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { log.info("Listener initialized"); } @Override public void contextDestroyed(ServletContextEvent sce) { log.info("Listener destroyed"); } // business logic }
这时候如果Job服务被停止之后,不会打印Listener destroyed
排查顺序
- 检查web.xml配置顺序,确认是不是有别的Listener
- 没有
- 检查是不是缺少了@WebListener
- 这个和web.xml效果一样,如果有web.xml配置则不需要@WebListener
- 检查类加载器是不是加载错误了,在初始化方法里加
this.getClass().getClassLoader() sce.getServletContext().getClassLoader()
检查这两个是否是同一个路径下的java程序(jar包或者war包)
排查完发现都不是,后来发现是因为Slf4j框架在销毁过程之前已经被销毁了,所以log框架打的日志在contextDestroyed没有打印
或者用StackOverflow推荐的这个禁用auto-shutdown
解决办法
选择用System.out.println();

浙公网安备 33010602011771号