是用SpringBoot框架进行开发的时候,如果使用ServletContextListener对spring启动前和停止前做一些清理工作的时时候,需要用到一些autowired的类,测试发现这些类在启动的时候,由于相应的beanfactory还没有加载,所以会出现问题。找了一段时间,发现下面的方法能够有效解决这个问题。解决办法也是参照stackflow上面的。。
@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;
}按照上面的做法,就可以使用autowired了。
本文介绍了解决在SpringBoot框架下使用ServletContextListener进行启动前和停止前的操作时,如何有效利用autowired的类,避免由于beanfactory未加载导致的问题。通过实现ContextWebListener接口并重写contextInitialized和contextDestroyed方法,可以确保在启动和停止时正确地注入和使用依赖。实验证明,按照文中提供的方法操作后,即可顺利使用autowired的类。
1202

被折叠的 条评论
为什么被折叠?



