注解的办法虽然够用,但是对于老项目移植时兼容不是很好,所以可以写一个简单粗暴的类解决。
首先,在工具类中创建一个读取配置文件的工具类SystemConfigReader
public class SystemConfigReader {
private static Properties prop = null;
public static void init() {
try {
ClassPathResource classPathResource = new ClassPathResource("conf.properties");
prop = new Properties();
InputStream is = classPathResource.getInputStream();
prop.load(is);
is.close();
} catch (Exception e) {
System.out
.println("Can't read file stream, file name is conf.properties");
e.printStackTrace();
}
}
public static Properties getProp() {
if (null == prop)
init();
return prop;
}
/**
*
* @param key
* @return string value of the key
*/
/**
* get value by key
*
* @param key
* @return
*/
public static String getValueByKey(String key) {
getProp();
String s = prop.getProperty(key);
if (null != s) {
return s.trim();
} else {
System.out.println(" mino key value not founded , the key is :"
+ key);
return "";
}
}
}
读取的时候只需调用SystemConfigReader.getValueByKey(“key”)方法,也可以改造把方法抽象出来,做一个读取任意配置文件的工具类,都很简单,时间有限,我就不详细叙述了,第一次写博客,希望大家能用得到。