spring boot在view层使用公共属性

spring boot需要在view层使用公共属性,在其他项目中找到的源码:

  • 把所有公共属性放在ServletContext中
  • 实现ServletContextListener,ApplicationContextAware两个接口
  • ApplicationContextAware用来获取spring工厂中的bean
  • 每次数据更新调用方法,更新ServletContext中的数据
@Component("initSystem")
public class InitSystem implements ServletContextListener,ApplicationContextAware{

    private static ApplicationContext applicationContext;
    
    public static Map arcTypeMap=new HashMap();
    
    
    /**
     * 加载数据到application缓存中
     * @param application
     */
    public void loadData(ServletContext application){
        ArcTypeService arcTypeService=(ArcTypeService) applicationContext.getBean("arcTypeService");
        LinkService linkService=(LinkService) applicationContext.getBean("linkService");
        List arcTypeList=arcTypeService.listAll(Sort.Direction.ASC, "sort");
        application.setAttribute("allArcTypeList", arcTypeList); // 所有类别
        for(ArcType arcType:arcTypeList){
            arcTypeMap.put(arcType.getId(), arcType);
        }
        application.setAttribute("linkList", linkService.listAll(Sort.Direction.ASC,"sort")); // 所有友情链接
    }


    @Override
    public void contextInitialized(ServletContextEvent sce) {
        loadData(sce.getServletContext());
    }

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

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // TODO Auto-generated method stub
        this.applicationContext=applicationContext;
    }

}

你可能感兴趣的:(spring boot在view层使用公共属性)