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<Integer,ArcType> arcTypeMap=new HashMap<Integer,ArcType>();
    
    
    /**
     * 加载数据到application缓存中
     * @param application
     */
    public void loadData(ServletContext application){
        ArcTypeService arcTypeService=(ArcTypeService) applicationContext.getBean("arcTypeService");
        LinkService linkService=(LinkService) applicationContext.getBean("linkService");
        List<ArcType> 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;
    }

}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容