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