背景
在开发中,会遇到有些资源会放在静态资源中,在环境初始化时去初始化一次,从而可以共享给所有对象使用;但是在我们静态资源获取配置文件中的值时,不能采用Spring原始注解的方法@Value(${xxxx})获取,因为Static静态资源加载的顺序在Spring容器加载之前,所以无法读取中的值;如果需要静态资源获取properties中的值,需要借助PropertyUtil 工具类进行实现;
package ;
import org.;
import org.;
import .*;
import ;
/**
* Desc:properties文件获取工具类
* Created by on 2016/9/15.
*/
public class PropertyUtil {
private static final Logger logger = ();
private static Properties props;
static{
loadProps();
}
synchronized static private void loadProps(){
props = new Properties();
InputStream in = null;
try {
String path =("/").getPath();
//获取web-inf目录的路径
path=(1, ("classes"));
in = new FileInputStream(path+"");
(in);
} catch (FileNotFoundException e) {
("文件未找到");
} catch (IOException e) {
("出现IOException");
} finally {
try {
if(null != in) {
();
}
} catch (IOException e) {
("文件流关闭出现异常");
}
}
("加载properties文件内容完成...........");
("properties文件内容:" + props);
}
public static String getProperty(String key){
if(null == props) {
loadProps();
}
return (key);
}
public static String getProperty(String key, String defaultValue) {
if(null == props) {
loadProps();
}
return (key, defaultValue);
}
}
测试方法:
(“配置文件属性key值”);