1:启动项目时加载数据库数据到缓存中
大体思路:
1:自定义类实现InitializingBean接口
2:并追加注解@Component
3:set方法注入mapper
4:从数据库查出的数据放入map中
5:页面配置要改变的数据,修改后刷新map中的值,动态更新缓存数据
2:具体实现的代码如下
注意:需要引入自己的mapper查询结果
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @description: TestPropertiesInit 属性数据初始化:
* 实现InitializingBean接口,重写方法afterPropertiesSet()方法,可以在项目启动时进行加载
* @author:
* @create: 2020.2.25
*/
@Component("TestPropertiesInit")
public class TestPropertiesInit implements InitializingBean {
private static Logger logger = LoggerFactory.getLogger(TestPropertiesInit.class);
//项目启动加载数据存入map中
public static Map<String, String> map = new HashMap<String, String>();
public static Map<String, String> getMap() {
return map;
}
public static void setMap(Map<String, String> map) {
TestPropertiesInit.map = map;
}
private ConstantMapper constantMapper;
public ConstantMapper getConstantMapper() {
return constantMapper;
}
//采用set方式获取对象,不能采用autowire,项目启动时未初始化完成spring对象
@Resource
public void setConstantMapper(ConstantMapper constantMapper) {
this.constantMapper = constantMapper;
}
@Override
public void afterPropertiesSet() throws Exception {
logger.info("----初始化系统参数开始---------------start");
List<Constant> constants = this.constantMapper.queryAllCode();
for (Constant c : constants) {
map.put(c.getCode(), c.getValue());
//System.out.println("map====="+map.toString());
}
//System.out.println(map);
logger.info("----初始化系统参数结束--------success-------end" + map.toString());
}
}