将springboot打包为JAR时,ServletContextEvent.getServletContext返回null

时间:2018-05-13 04:01:10

标签: java spring-boot servlets

这是我实现CommandLineRunner和ServletContextListener的代码, 当springboot启动时,我想获取ServletContext并将数据放入其中。 在正常的情况下,这意味着没有打包到jar只是启动Idea IDE中的springboot是可以的,但是当我将它打包到jar时,sce.getServletContext()将为我返回NUll。如何解决这个问题呢? 感谢。

@Order(10)
@Component("startupRunner")
public class StartupRunner implements CommandLineRunner, ServletContextListener {

    private ServletContext application = null;

    @Resource
    private FilmService filmService;

    @Resource
    private WebSiteInfoService webSiteInfoService;

    @Resource
    private LinkService linkService;

    @Autowired
    private WebSiteService webSiteService;

    @Override
    public void run(String... args) throws Exception {
        this.loadData();
    }


    public void loadData() {
        System.out.println("vincent.applicaiton" + application);
        application.setAttribute("newestInfoList", webSiteInfoService.list(null, 0, 10));
        Film film = new Film();
        film.setHot(1);
        application.setAttribute("newestHotFilmList", filmService.list(film, 0, 10));
        application.setAttribute("newestIndexHotFilmList", filmService.list(film, 0, 32));
        application.setAttribute("newestWebSiteList", webSiteService.newestList(0, 10));
        application.setAttribute("newestFilmList", filmService.list(null, 0, 10);
        application.setAttribute("linkList", linkService.listAll());
    }

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        //WebApplicationContext requiredWebApplicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(sce.getServletContext());
        //application= requiredWebApplicationContext.getServletContext();
        application = sce.getServletContext();

    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        // TODO Auto-generated method stub

    }

}

1 个答案:

答案 0 :(得分:0)

我使用一种愚蠢的方法来解决这个问题,即

@Override
public void run(String... args) throws Exception {
    if (application != null)
        this.loadData();
}

当使用mevan打包springboot我做验证时,这个动作可以避免零点异常。谁有更优雅的解决方案?