Resource與ResourceLoader對比
1、Resource接口定義了應用訪問底層資源的能力。
- 通過FileSystemResource以文件系統絕對路徑的方式進行訪問;
- 通過ClassPathResource以類路徑的方式進行訪問;
- 通過ServletContextResource以相對於Web應用根目錄的方式進行訪問。
在獲取資源后,用戶就可以通過Resource接口定義的多個方法訪問文件的數據和其他的信息:如可以通過getFileName()獲取文件名,通過getFile()獲取資源對應的File對象,通過getInputStream()直接獲取文件的輸入流。此外,還可以通過createRelative(String relativePath)在資源相對地址上創建新的文件。
2、ResourceLoader接口提供了一個加載文件的策略。它提供了一個默認的實現類DefaultResourceLoader,獲取資源代碼如下:
1 @Override 2 public Resource getResource(String location) { 3 Assert.notNull(location, "Location must not be null"); 4 if (location.startsWith("/")) { 5 return getResourceByPath(location); 6 } 7 else if (location.startsWith(CLASSPATH_URL_PREFIX)) { 8 return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader()); 9 } 10 else { 11 try { 12 // Try to parse the location as a URL... 13 URL url = new URL(location); 14 return new UrlResource(url); 15 } 16 catch (MalformedURLException ex) { 17 // No URL -> resolve as resource path. 18 return getResourceByPath(location); 19 } 20 } 21 }
1 protected Resource getResourceByPath(String path) { 2 return new ClassPathContextResource(path, getClassLoader()); 3 }