Springboot ServletContextListener @Autowired null 解决办法

来源:互联网 发布:python股票自动交易 编辑:程序博客网 时间:2024/05/21 19:22

是用SpringBoot框架进行开发的时候,如果使用ServletContextListener对spring启动前和停止前做一些清理工作的时时候,需要用到一些autowired的类,测试发现这些类在启动的时候,由于相应的beanfactory还没有加载,所以会出现问题。找了一段时间,发现下面的方法能够有效解决这个问题。解决办法也是参照stackflow上面的。。

@WebListenerpublic class ContextWebListener implements ServletContextListener {@Overridepublic void contextDestroyed(ServletContextEvent arg0) {// TODO Auto-generated method stubLogHelper.info("web stop!");System.out.println("dao++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");}@Overridepublic void contextInitialized(ServletContextEvent sce) {// TODO Auto-generated method stub// SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);WebApplicationContextUtils.getRequiredWebApplicationContext(sce.getServletContext()).getAutowireCapableBeanFactory().autowireBean(this);LogHelper.info("web start!");System.out.println("dao++++"+dao.count());LogHelper.info("web start! finish");}@Autowiredprivate ApplicationMetricsDao dao;}

按照上面的做法,就可以使用autowired了。


1 0