先說說Resource接口
Spring框架內的org.springframework.core.io包下的Resource接口是作爲所有資源的抽象和訪問接口。
Resource接口的定義
public interface Resource extends InputStreamSource {
boolean exists();
boolean isReadable();
boolean isOpen();
URL getURL() throws IOException;
URI getURI() throws IOException;
File getFile() throws IOException;
long contentLength() throws IOException;
Resource createRelative(String relativePath) throws IOException;
String getFilename();
String getDescription();
}
該接口定義了7個方法,可以幫助我們查詢資源狀態、訪問資源內容等等。可以根據資源的不同類型,或者資源所處的不同場合,給出相應的具體實現類。資源有了,再來看看如何去查找和定位這些資源,這個時候我們的ResourceLoader就閃亮登場了。
ResourceLoader 統一資源定位器
org.springframework.core.io.ResourceLoader接口是資源查找定位策略的統一抽象。
ResourceLoader接口定義
public interface ResourceLoader {
String CLASSPATH_URL_PREFIX = ResourceUtils.CLASSPATH_URL_PREFIX;
Resource getResource(String location);
ClassLoader getClassLoader();
}
這裏面最主要的就是getResource()方法,通過它我們就可以根據指定的資源位置,定位到具體的資源實例。
上面說過ResourceLoader接口是提供資源查找策略的統一 抽象,具體資源查找策略則由相應的ResourceLoader實現類給出,它默認的實現類是DefaultResourceLoader。下面用具體的代碼來演示利用ResourceLoader實現類來讀取配置文件的屬性。
demo演示
先在項目根目錄下的application.properties裏面寫如下內容
project.name=myproject
然後是java代碼
/**
* *
* @ClassName PropertyUtil.java
* <p>Description: </p>
* @author 沉魚
* @date 2017年11月30日 下午4:15:49
*/
public class PropertyUtil {
private static final String PROPERTY_LOCATION = "classpath:application.properties";
public static String getProperyies(String key) throws IOException{
DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
Resource resource = resourceLoader.getResource(PROPERTY_LOCATION);
ResourcePropertySource properties = new ResourcePropertySource(resource);
Map<String,Object> map = properties.getSource();
return map.get(key).toString();
}
public static void main(String[] args) throws IOException {
System.out.println(getProperyies("project.name"));
}
}
啓動main方法後,控制檯會打印myproject
說明:ResourcePropertySource這個類最好看一下源碼,它一層一層有繼承EnumerablePropertySource<Map<String, Object>這個類,然後EnumerablePropertySource<Map<String, Object>>,又繼承PropertySource<T>抽象類
PropertySource抽象類部分定義
public abstract class PropertySource<T> {
protected final String name;
protected final T source;
...
}
其實ResourcePropertySource這個類有直接提供,只需要一個資源路徑的構造方法
public ResourcePropertySource(String location) throws IOException {
this(new DefaultResourceLoader().getResource(location));
}
所以上面代碼可以直接替換成下面這樣的,得到結果是一樣,
public class PropertyUtil {
private static final String PROPERTY_LOCATION = "classpath:application.properties";
public static String getProperyies(String key) throws IOException{
ResourcePropertySource properties = new ResourcePropertySource(resource);
Map<String,Object> map = properties.getSource();
return map.get(key).toString();
}
public static void main(String[] args) throws IOException {
System.out.println(getProperyies("project.name"));
}
}
但這麼做,跟本文標題ResourceLoader似乎沒有什麼關係啦(o_o),不過按上面的寫法顯得對底層瞭解多一些哈哈。
好了,以後在工作項目中,想獲得配置文件中的屬性值,可以像上面一樣自己寫一個工具類,然後就裝X去吧。