java加载静态properties的方法

因为今天在项目中用到了该方法、作为一个小白、就顺手记下来当作笔记。

我们项目中是把这些静态资源、一些配置文件放在system.properties文件中,因为这些资源基本不会变动、并且很多地方都有引用到了,改变不易 。

废话不多、开始

 1 public void InitSystem(){
 2 
 3  
 4              ClassLoader cl = Thread.currentThread().getContextClassLoader();
 5              Properties properties = new Properties();
 6 
 7              InputStream in = null;
 8              try{
 9                  in = cl.getResourceAsStream("wechat.properties");
10                  properties.load(in);
11                  for (Object o : properties.keySet()){
12                      Constants.wxProperties.put( o , properties.get(o));
13                  }
14                  logger.info("加载微信配置文件完成...");
15 
16                  properties = new Properties();
17                  in = cl.getResourceAsStream("redis.properties");
18                  properties.load(in);
19                  for(Object o : properties.keySet()){
20                      Constants.redisProperties.put(o , properties.get(o));
21                  }
22                  logger.info("加载redis配置文件完成...");
23 
24 
25 
26              }catch (IOException e){
27                 logger.error("[fail] load system properties failed" );
28                 e.printStackTrace();
29              }finally {
30                  if(in != null){ //在此处关闭流
31                     try {
32                        in.close();
33                     }catch (IOException e){
34                         logger.error("[error] a error happened in close inputStream ");
35                         e.printStackTrace();
36                     }
37                  }
38              }
39 
40 }

而在上面的Contstants.wxPropertis是定义在公用文件中的

 1 public class Constants{
 2  /**
 3      * 加载微信基本信息
 4      */
 5     public static  Map<Object , Object> wxProperties = new HashMap<Object, Object>();
 6 
 7 
 8     /**
 9      * 加载redis配置文件
10      */
11     public static Map<Object , Object> redisProperties = new HashMap<Object, Object>();
12 
13 
14 }

这样我们就可以在加载系统文件的时候把这些加载在内存中、然后后面再用到的时候、直接用就好了。

 

转载于:https://www.cnblogs.com/mzlb520/p/9879817.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值