其实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;
}
}