Java通过HashMap只加载一次常量(单例模式)

通常我们的项目中有很多数据或者常量,在项目启动后只需要加载一次,若通过普通的查询方法,每次获取都与数据库交互必定影响效率;

故考虑用以下方法,仅第一次加载会查询数据库,再次获取这些常量或数据时,会从缓存的Map中取值,明显提升速度。

单例模式的一种实现方式:利用静态HashMap和reload变量来实现。

 1 //系统参数
 2 
 3 public class SysParameter{
 4     private static final HashMap<String,SysParameter> tagMap = new HashMap<String,SysParameter>();
 5 
 6     private String key; // 参数名
 7     private String value; // 参数值
 8     
 9     private static final SysParameter NULL = new SysParameter("","");
10 
11     private static final String sql = "select key, value from TABLENAME where ChoSign ='Y' ";
12     private static boolean reload = false;
13     
14     public String getKey(){
15         return key;
16     }
17     
18     public void setKey(String key){
19         this.key = key;
20     }
21     public String getValue(){
22         return key;
23     }
24     
25     public void setValue(String Value){
26         this.value = value;
27     }
28 
29     // 构造函数
30     private SysParameter(){
31         tagMap.clear();
32         List<RowMap> sysParamList = DBSql.getMaps(sql, new HashMap<String, Object>());//此处可使用 Spring Jdbc Template实现数据库查询
33 
34         if(sysParamList != null && sysParamList.size() > 0){
35             for(RowMap rm : sysParamList){
36                 SysParameter sysParam = new SysParameter(rm.getString("key"),rm.getString("value"));
37                 tagMap.put(sysParam.getKey(),sysParam); //存入HashMap中
38             }
39         }
40         raload = true;
41     }
42 
43     // 根据key得到代码类
44     public static SysParameter getSysParameterByKey(String key){
45         if(!reload){ //仅第一次进入才调用构造方法,查询数据
46             new SysParameter;
47         }
48         SysParameter sysParam = (SysParameter)tagMap.get(key);
49         if(sysParam == null){
50             return NULL;
51         }
52         return sysParam;
53     }
54 
55     // String.equalsIgnoreCase("Y"); 忽略大小写匹配
56 
57     // 带参数的构造函数
58     private SysParameter(String key, String value){
59         this.setKey(key);
60         this.setValue(valuee);
61     }
62 }
如果对你有帮助,点个"推荐"呗~
如果发现不当之处,欢迎不吝赐教~
转载请注明出处哦~
原文地址:https://www.cnblogs.com/imone/p/getparameter.html