# 2.4. ResourceLoader接口

`ResourceLoader`接口旨在由可以返回（即加载）`Resource`实例的对象实现。以下清单显示了`ResourceLoader` 接口定义：

```java
public interface ResourceLoader {

    Resource getResource(String location);

    ClassLoader getClassLoader();
}
```

所有应用程序上下文都实现了该`ResourceLoader`接口。因此，所有应用程序上下文都可以用于获取`Resource`实例。

当您调用`getResource()`特定的应用程序上下文，并且指定的位置路径没有特定的前缀时，您将返回`Resource`适合该特定应用程序上下文的类型。例如，假设下面的代码片段是针对一个`ClassPathXmlApplicationContext`实例运行的：

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

针对 `ClassPathXmlApplicationContext`，该代码返回 `ClassPathResource`。如果对`FileSystemXmlApplicationContext`实例运行相同的方法，它将返回一个`FileSystemResource`. 对于 `WebApplicationContext`，它将返回 `ServletContextResource`。它同样会为每个上下文返回适当的对象。

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

另一方面，您也可以通过指定`classpath:`特殊前缀来强制使用`ClassPathResource`，无论应用程序上下文类型如何，如以下示例所示：

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

同样，您可以通过指定任何标准 `java.net.URL`前缀来强制使用 `UrlResource`。以下示例使用`file`和`https`前缀：

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

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

下表总结了将`String`对象转换为`Resource` 对象的策略：

| 前缀         | 例子                               | 解释                                                                                                                                                                 |
| ---------- | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| classpath: | `classpath:com/myapp/config.xml` | 从类路径加载。                                                                                                                                                            |
| file:      | `file:///data/config.xml`        | 从文件系统加载为 `URL`。另请参阅[`FileSystemResource`注意事项](https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#resources-filesystemresource-caveats)。 |
| https:     | `https://myserver/logo.png`      | 加载为`URL`.                                                                                                                                                          |
| 无          | `/data/config.xml`               | 取决于底层`ApplicationContext`。                                                                                                                                         |

####
