# 2.2资源接口

Spring的资源接口是一个更强大的接口，用于抽象对低级资源的访问。以下列表显示了资源接口定义：

```
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();

}
```

Resource继承了InputStreamSource接口，下面是其定义：

```
public interface InputStreamSource {

    InputStream getInputStream() throws IOException;

}
```

Resource的比较重要的方法如下：

* getInputStream(): 定位和打开resource， 返回InputStream 来读取资源。每一次调用都会返回一个新的InputStream，调用者负责将其关闭。
* exists(): 返回boolean，用来判断资源是否存在
* isOpen(): 返回boolean，用来判断资源是不是已经存在一个open stream处理器。 true表明InputStream不能被多次读取，那么这次的读取会被关闭，以避免资源泄露。false是所有正常资源实现的返回，有可能会抛异常：InputStreamResource。
* getDescription(): 返回资源的描述，用于错误输出。通常这会返回resource URL的全名。

其他的方法可以让你获取到代表resource的URL或者File对象。

Spring本身广泛使用Resource抽象，当需要资源时，它在许多方法签名中作为参数类型。某些Spring API中的其他方法（如各种ApplicationContext实现的构造函数）采用字符串，该字符串以未加修饰或简单的形式用于创建适合该上下文实现的资源，或者通过String路径上的特殊前缀让调用方指定必须创建特定的Resource实现。

尽管在Spring中经常使用Resource接口，但在你自己的代码中单独使用作为通用实用程序类来访问资源实际上非常有用，即使你的代码不知道或不关心Spring的任何其他部分。虽然这将你的代码与Spring结合在一起，但它实际上只将它与这一小组实用程序类结合在一起，这些实用程序类可以作为URL的更强大的替代，并且可以被视为等同于为此目的而使用的任何其他库。

> Resource抽象并没有替代方法，它尽可能的使用包装。比如：UrlResource 包装了URL，然后使用被包装的URL去工作。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.flydean.com/spring-framework-documentation5/core-technologies/2.resources/2.2resource-interface.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
