【问题标题】:When packaging springboot as JAR, the ServletContextEvent.getServletContext returns null [duplicate]将springboot打包为JAR时,ServletContextEvent.getServletContext返回null [重复]
【发布时间】:2018-05-13 04:01:09
【问题描述】:

这是我实现 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

    }

}

【问题讨论】:

    标签: java spring-boot servlets


    【解决方案1】:

    我用一个笨方法来解决这个问题,就是

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

    在使用mevan打包springboot的时候我做了验证,这个动作可以避免空点异常。有人有更优雅的解决方案吗?

    【讨论】:

      猜你喜欢
      • 2013-09-20
      • 1970-01-01
      • 2017-05-24
      • 1970-01-01
      • 1970-01-01
      • 2022-01-11
      • 2011-02-07
      • 2019-10-04
      • 2011-11-01
      相关资源
      最近更新 更多