怎么样使常量的值变成可以变化的!

其实spring框架自己提供了@Value的注解,只需要把那些API的路径或是其他的值写在.properties配置文件中,但是并不知道@Value的原理,下面写一个小demo

public static class CONFIGS{
            private static Map<String,String> datas=new HashMap<String,String>();
            private static PropsUtil pt=new PropsUtil("/conf.properties");
 // ReflectTest.class.getResourceAsStream(String path): path不以’/'开头时默认是从此类所在的包下取资源,以’/'开头则是从ClassPath根下获取。

            private static String GET(String name){//name是一个常量
                String res=null;
                if(!datas.containsKey(name)){//取反hashmap中要是没有就返回true;
                    datas.put(name,pt.readSingleProps(name));//用name这个常量做key,value要跑到readSingleProps方法里卖去获取配置文件之后对应的属性值,不过配置文件中的值是可以改变的,下面来看下PropsUtil 类吧!
                }
                res=datas.get(name);
                return res;
                
            }
            
        }

 

PropsUtil:主要包含以下4个方法:

public class PropsUtil{

private String filePath;//文件地址

//编写一个有参构造方法初始化获得文件地址

public PropsUtil(String filename){

      filePath=filename;

//编写一个方法通过java的反射机制用文件名去获取文件byte

private inputStream getProperty(){

          return this.getClass().getResourceAsStream(filePath);

  }

 

//这个方法就是最后根据key获取值的方法

public String loadingPropperties(String name){

String value="";

Properties ps=new Properties();//

try{

inputStream fi=getPropsIS();//获取流

            ps.load(fi);
            fi.close();
           value = ps.getProperty(name);

}catch(Exception e){

         value=null;

}

return value;

}

 

 

public Map<String,String> readAllProps() {
        Map<String,String> h = new HashMap<String,String>();
        Properties props = new Properties();
        try {
            InputStream fi = getPropsIS();
            props.load(fi);
            fi.close();
            @SuppressWarnings("unchecked")
            Enumeration<String> er = (Enumeration<String>) props.propertyNames();
            while (er.hasMoreElements()) {
                String paramName = (String) er.nextElement();
                h.put(paramName, props.getProperty(paramName));
            }
        } catch (Exception e) {
            h = new HashMap<String,String>();
        }
        return h;
    }

 

 

}

 

 

 

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值