# 2.4ResourceLoader

ResourceLoader用来返回Resource实例，下面是其定义：

```
public interface ResourceLoader {

    Resource getResource(String location);

}
```

所有的 application contexts 都实现了ResourceLoader类。因此所有的application contexts 都可以用来获取Resource。

当你在特定的应用程序上下文上调用getResource（），并且指定的位置路径没有特定的前缀时，你将返回适合该特定应用程序上下文的资源类型。例如，假设对ClassPathXmlApplicationContext实例执行了以下代码片段：

```
Resource template = ctx.getResource("some/resource/path/myTemplate.txt");
```

在ClassPathXmlApplicationContext中，这个方法返回ClassPathResource，如果在FileSystemXmlApplicationContext中，方法返回FileSystemResource。 在WebApplicationContext， 方法返回ServletContextResource。 他会返回和ApplicationContext相对应的Resource实现。

因此，你可以以适合特定应用程序上下文的方式加载资源。

当然，你可以强制ClassPathResource使用，而不管ApplicationContext到底是什么。这样做你需要添加classpath:前缀。如下：

```
Resource template = ctx.getResource("classpath:some/resource/path/myTemplate.txt");
```

同样的，你可以强制使用UrlResource通过添加标准的java.net.URL前缀。

```
Resource template = ctx.getResource("file:///some/resource/path/myTemplate.txt");

Resource template = ctx.getResource("https://myhost.com/resource/path/myTemplate.txt");
```

下面是将String转换为Resource的策略：

| Prefix     | Example                        | Explanation              |
| ---------- | ------------------------------ | ------------------------ |
| classpath: | classpath:com/myapp/config.xml | 从classpath加载             |
| file:      | file:///data/config.xml        | 从文件系统以URL方式加载            |
| http:      | <https://myserver/logo.png>    | URL方式加载                  |
| (none)     | /data/config.xml               | 依赖于ApplicationContext实现。 |
