Spring --- Resource

一)如何使用spring中的resource
Spring的資源文件訪問功能使用起來十分簡單,調用ApplicationContext.getResource的方法即可:
Java代碼 複製代碼 收藏代碼
  1. Resource template = ctx.getResource("some/resource/path/myTemplate.txt");
  2. Resource template = ctx.getResource("classpath:some/resource/path/myTemplate.txt");
  3. Resource template = ctx.getResource("file:/some/resource/path/myTemplate.txt");
  4. Resource template = ctx.getResource("http://myhost.com/resource/path/myTemplate.txt");


二)resource的深入瞭解
其實知道了以上的gerResource方法,就已經能夠滿足我們日常的資源文件訪問的需要了。但本着精益求精的精神,我們不妨看下spring的源碼,看看spring到底是如何實現這個功能模塊的。首先是接口Resource:
Java代碼 複製代碼 收藏代碼
  1. public interface Resource extends InputStreamSource {
  2. boolean exists();
  3. boolean isOpen();
  4. URL getURL() throws IOException;
  5. File getFile() throws IOException;
  6. Resource createRelative(String relativePath) throws IOException;
  7. String getFilename();
  8. String getDescription();
  9. }
  10. public interface InputStreamSource {
  11. InputStream getInputStream() throws IOException;
  12. }

基於這個底層接口,spring運用多態繼承了一系列的子類以滿足不同形式的資源文件訪問:
UrlResource: file: http: ftp: 的資源訪問形式都是它處理啦
ClassPathResource: 看名字也猜的出來classpath:的資源訪問形式就是它處理的
FileSystemResource: 從文件系統路徑獲取資源文件,C:\XXXXX
ServletContextResource: web應用中從context下獲取資源文件,相對路徑絕對路徑均可
InputStreamResource: 缺省的Resource類,如果根據輸入的url形式找不到對應的Resource,那麼就調用它了...當然我們也可以顯示的調用它:
Java代碼 複製代碼 收藏代碼
  1. @Test
  2. public void testInputStreamResource() {
  3. ByteArrayInputStream bis = new ByteArrayInputStream("Hello World!".getBytes());
  4. Resource resource = new InputStreamResource(bis);
  5. if(resource.exists()) { ...... }
  6. }


ByteArrayResource: 看代碼便知...
Java代碼 複製代碼 收藏代碼
  1. @Test
  2. public void testByteArrayResource() {
  3. Resource resource = new ByteArrayResource("Hello World!".getBytes());
  4. if(resource.exists()) { ...... }
  5. }


三)ResourceLoaderAware
和其它Aware一樣,繼承此接口後,當此bean實例化時會自動調用setResourceLoader(ResourceLoader resourceLoader)方法。
Java代碼 複製代碼 收藏代碼
  1. public interface ResourceLoaderAware {
  2. void setResourceLoader(ResourceLoader resourceLoader);
  3. }


四) Resource的注入
那麼,如果是一個resouce類,Spring在配置文件中改如何處理以使它自動注入呢?樣例如下:
Java代碼 複製代碼 收藏代碼
  1. <bean id="myBean" class="...">
  2. <property name="template" value="some/resource/path/myTemplate.txt"/>
  3. </bean>
  4. <property name="template" value="classpath:some/resource/path/myTemplate.txt">
  5. <property name="template" value="file:/some/resource/path/myTemplate.txt"/>

十分方便吧~~

五)資源文件的通配樣式
當你需要一次獲取多個資源文件時,你可以考慮採用以下一些通配的手段:
Java代碼 複製代碼 收藏代碼
  1. /WEB-INF/*-context.xml
  2. com/mycompany/**/applicationContext.xml
  3. file:C:/some/path/*-context.xml
  4. classpath:com/mycompany/**/applicationContext.xml
  5. classpath*:conf/appContext.xml //獲取classpath內所有的conf/appContext.xml,不加*的話只會加載搜索時遇到的第一個匹配文件
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章