zoukankan      html  css  js  c++  java
  • Spring中使用 InitializingBean

    想在后台中设置一个全局的缓存,即要缓存的数据仅在整个项目中初始化一次,最简单的做法就是将变量声明为 static 类型。

    使用 staic 是存在局限性的,它的初始化顺序在 spring 注入实例之前,有时想在项目启动的时候,从数据库中查处数据,并且设置为缓存,那 static 估计要靠边了。

    使用 InitializingBean 轻松解决这个问题。具体用法如下:

    @Service
    public class CacheBean implements InitializingBean {
    
        @Autowired
        InfoStationRepository infoStationRepository;
    
        private Logger logger = LoggerFactory.getLogger(getClass());
    
        private List<InfoStation> infoStationList;
    
        public List<InfoStation> getInfoStationList() {
            return infoStationList;
        }
    
        public void setInfoStationList(List<InfoStation> infoStationList) {
            this.infoStationList = infoStationList;
            logger.info("缓存站点信息数据成功!");
        }
    
        private void loadCache(){
            setInfoStationList(infoStationRepository.findAll());
        }
    
        @Override
        public void afterPropertiesSet() throws Exception {
            loadCache();
        }
    }
  • 相关阅读:
    目录路径加反斜杠和不加的区别
    window端口号被占用解决
    个人博客设计记录
    2017/12/15
    添加code到github上
    跨域简介
    客户端存储
    window.name跨域
    BZOJ1305: [CQOI2009]dance跳舞
    BZOJ4872: [Shoi2017]分手是祝愿
  • 原文地址:https://www.cnblogs.com/unique1319/p/8311221.html
Copyright © 2011-2022 走看看