最近用springboot做了一个服装推荐网,发现了一个奇葩问题,在这里记录一下。
问题现象如下:
如果StartupRunner implements CommandLineRunner,ServletContextListener,那么windows下开发环境正常,application是有值的,不为空;
但是一旦将该工程达成war包,找个tomcat服务器运行,那么application就是null了,
后面通过查阅资料,得到结论,只要implements CommandLineRunner,那么这个类(StartupRunner)就会伴随tomcat启动而加载运行,相当于
一个监听器,同时还能当做spring所管理的组件来用,可以将application直接注入到当前类来;
最终代码如下
package com.javaxl.clothes.component; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; import com.javaxl.clothes.entity.Clothes; import com.javaxl.clothes.entity.ClothesType; import com.javaxl.clothes.service.ClothesService; import com.javaxl.clothes.service.ClothesTypeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; import org.springframework.web.context.support.WebApplicationContextUtils; import java.util.List; @Component("startupRunner") public class StartupRunner implements CommandLineRunner{ @Autowired private ServletContext application; @Autowired private ClothesService clothesService; @Autowired private ClothesTypeService clothesTypeService; @Override public void run(String... args) throws Exception { this.loadData(); } /** * 加载数据到applicaton缓存中 */ public void loadData(){ Clothes clothes = new Clothes(); clothes.setHot(1); // 水平导航栏展示(6个分类) List<ClothesType> clothesTypeMenus = clothesTypeService.list(null, 0, 6); // 首页最新最热的32种服装 List<Clothes> newestIndexHotClothesList = this.clothesService.list(clothes, 0, 32); // 右侧最新的10种服装 List<Clothes> newestClothesList = this.clothesService.list(null, 0, 16); // 右侧最新最热的10中服装 List<Clothes> newestHotClothesList = this.clothesService.list(clothes, 0, 16); application.setAttribute("clothesTypeMenus",clothesTypeMenus); application.setAttribute("newestIndexHotClothesList",newestIndexHotClothesList); application.setAttribute("newestClothesList",newestClothesList); application.setAttribute("newestHotClothesList",newestHotClothesList); } // @Override // public void contextInitialized(ServletContextEvent sce) { // application=sce.getServletContext(); // WebApplicationContextUtils.getRequiredWebApplicationContext(sce.getServletContext()) // .getAutowireCapableBeanFactory().autowireBean(this); // } // // @Override // public void contextDestroyed(ServletContextEvent sce) { // // } }
over....
备案号:湘ICP备19000029号
Copyright © 2018-2019 javaxl晓码阁 版权所有