---
title: "Spring --- Resource"
author: "thaIm"
date: "2012-12-06T16:50:18Z"
tags: []
categories: ["编程语言"]
slug: "spring-resource"
draft: false
lastmod: "2012-12-06T16:51:01Z"
id: 1743143
url: "https://thaim.iteye.com/blog/1743143"
---

一）如何使用spring中的resource
   Spring的资源文件访问功能使用起来十分简单,调用ApplicationContext.getResource的方法即可：

```java
Resource template = ctx.getResource("some/resource/path/myTemplate.txt");
Resource template = ctx.getResource("classpath:some/resource/path/myTemplate.txt");
Resource template = ctx.getResource("file:/some/resource/path/myTemplate.txt");
Resource template = ctx.getResource("http://myhost.com/resource/path/myTemplate.txt");
```


二）resource的深入了解
    其实知道了以上的gerResource方法，就已经能够满足我们日常的资源文件访问的需要了。但本着精益求精的精神，我们不妨看下spring的源码，看看spring到底是如何实现这个功能模块的。首先是接口Resource:

```java
public interface Resource extends InputStreamSource {
  boolean exists();
  boolean isOpen();
  URL getURL() throws IOException;
  File getFile() throws IOException;
  Resource createRelative(String relativePath) throws IOException;
  String getFilename();
  String getDescription();
}
public interface InputStreamSource {
  InputStream getInputStream() throws IOException;
}
```

   基于这个底层接口，spring运用多态继承了一系列的子类以满足不同形式的资源文件访问：
  UrlResource:  file:   http:   ftp: 的资源访问形式都是它处理啦
  ClassPathResource：  看名字也猜的出来classpath：的资源访问形式就是它处理的
  FileSystemResource： 从文件系统路径获取资源文件，C:\XXXXX
  ServletContextResource: web应用中从context下获取资源文件，相对路径绝对路径均可
  InputStreamResource： 缺省的Resource类，如果根据输入的url形式找不到对应的Resource,那么就调用它了...当然我们也可以显示的调用它：

```java
@Test  
public void testInputStreamResource() {  
   ByteArrayInputStream bis = new ByteArrayInputStream("Hello World!".getBytes());  
   Resource resource = new InputStreamResource(bis);  
   if(resource.exists()) {   ......  }    
}
```


  ByteArrayResource: 看代码便知...

```java

  @Test
  public void testByteArrayResource() {
    Resource resource = new ByteArrayResource("Hello World!".getBytes());
    if(resource.exists()) { ...... }
  }
```


三）ResourceLoaderAware
  和其它Aware一样，继承此接口后，当此bean实例化时会自动调用setResourceLoader(ResourceLoader resourceLoader)方法。

```java
public interface ResourceLoaderAware {
  void setResourceLoader(ResourceLoader resourceLoader);
}
```


四） Resource的注入
  那么，如果是一个resouce类，Spring在配置文件中改如何处理以使它自动注入呢？样例如下：

```java
<bean id="myBean" class="...">
  <property name="template" value="some/resource/path/myTemplate.txt"/>
</bean>

<property name="template" value="classpath:some/resource/path/myTemplate.txt">
<property name="template" value="file:/some/resource/path/myTemplate.txt"/>
```

  十分方便吧~~

五）资源文件的通配样式
  当你需要一次获取多个资源文件时，你可以考虑采用以下一些通配的手段：

```java
/WEB-INF/*-context.xml
com/mycompany/**/applicationContext.xml
file:C:/some/path/*-context.xml
classpath:com/mycompany/**/applicationContext.xml
classpath*:conf/appContext.xml  //获取classpath内所有的conf/appContext.xml,不加*的话只会加载搜索时遇到的第一个匹配文件
```