【发布时间】: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