引入 ServletContextListener @Autowired null 解决办法
public class ScheduleController implements ServletContextListener { @Autowired private ScheduleService scheduleService; @Override public void contextDestroyed(ServletContextEvent event) { System.out.println("销毁"); } @Override public void contextInitialized(ServletContextEvent event) { WebApplicationContextUtils.getRequiredWebApplicationContext(event.getServletContext()) .getAutowireCapableBeanFactory().autowireBean(this); System.out.println("开始执行周期任务"); scheduleService.start(); ; } }
如果使用ServletContextListener对spring启动前和停止前做一些清理工作的时时候,需要用到一些autowired的类,测试发现这些类在启动的时候,由于相应的beanfactory还没有加载,所以会出现问题。