是用SpringBoot框架进行开发的时候,如果使用ServletContextListener对spring启动前和停止前做一些清理工作的时时候,需要用到一些autowired的类,测试发现这些类在启动的时候,由于相应的beanfactory还没有加载,所以会出现问题。找了一段时间,发现下面的方法能够有效解决这个问题。解决办法也是参照stackflow上面的。。
[java] view plain copy
- @WebListener
- public class ContextWebListener implements ServletContextListener {
- @Override
- public void contextDestroyed(ServletContextEvent arg0) {
- // TODO Auto-generated method stub
- LogHelper.info("web stop!");
- System.out.println("dao++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
- }
- @Override
- public 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");
- }
- @Autowired
- private ApplicationMetricsDao dao;
- }