熟悉spring的人都知道, spring把配置文件等抽象为了Resource,然后对Resource做了扩充,包括文件资源,网络资源等等。加载配置文件有时候由于打包等原因导致读取不到配置文件等问题经常遇到,现在使用spring的ResourceLoader来解决这块的问题。
1. 加载文件:
使用FileSystemResourceLoader加载文件;
2. 加载classpath文件:
使用ClassPathResourceLoader加载文件(包括打包之后在JAR包里的配置文件);
但是这样很难记,spring做了路由, 直接使用DefaultResourceLoader就OK, 代码如下:
加载classpath下(包括jar包中的文件)
加载文件:只要把String locationPattern = "classpath:ognl/wei.properties";换成String locationPattern = "file:ognl/wei.properties";就正常了
1. 加载文件:
使用FileSystemResourceLoader加载文件;
2. 加载classpath文件:
使用ClassPathResourceLoader加载文件(包括打包之后在JAR包里的配置文件);
但是这样很难记,spring做了路由, 直接使用DefaultResourceLoader就OK, 代码如下:
加载classpath下(包括jar包中的文件)
@Test
public void testClassPathPropertyFile() throws IOException {
String locationPattern = "classpath:ognl/wei.properties";
ResourceLoader loader = new DefaultResourceLoader();
Resource resource = loader.getResource(locationPattern);
Properties prop = new Properties();
prop.load(resource.getInputStream());
for (Object key : prop.keySet()) {
System.out.println("key:" + key + ", value:"
+ prop.getProperty((String) key));
}
}
加载文件:只要把String locationPattern = "classpath:ognl/wei.properties";换成String locationPattern = "file:ognl/wei.properties";就正常了