引入 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尚未加载,因此会出现问题。

相关文章
相关标签/搜索