# 2.6. ResourceLoaderAware接口

`ResourceLoaderAware`接口是一个特殊的回调接口，用于标识期望提供`ResourceLoader`引用的组件。以下清单显示了`ResourceLoaderAware`接口的定义：

```java
public interface ResourceLoaderAware {

    void setResourceLoader(ResourceLoader resourceLoader);
}
```

当一个类实现`ResourceLoaderAware`并部署到应用程序上下文（作为 Spring 管理的 bean）中时，它被应用程序上下文识别为`ResourceLoaderAware`。然后应用程序上下文调用`setResourceLoader(ResourceLoader)`，将自己作为参数提供（请记住，Spring 中的所有应用程序上下文都实现了该`ResourceLoader`接口）。

由于 `ApplicationContext`是一个 `ResourceLoader`，因此 bean 也可以实现 `ApplicationContextAware`接口并直接使用提供的应用程序上下文来加载资源。但是，一般来说，如果您只需要专用接口，最好使用`ResourceLoader` 专用接口。该代码将仅与资源加载接口（可以认为是实用程序接口）耦合，而不与整个 Spring `ApplicationContext`接口耦合。

在应用程序组件中，您还可以依赖 `ResourceLoader` 的自动装配作为实现`ResourceLoaderAware`接口的替代方法。传统的构造函数和 byType 自动装配模式（如自动装配协作者中所述）能够分别为构造函数参数或 setter 方法参数提供 `ResourceLoader`。为了获得更大的灵活性（包括自动装配字段和多个参数方法的能力），请考虑使用基于注解的自动装配功能。在这种情况下，只要相关字段、构造函数或方法带有 `@Autowired` 注解，`ResourceLoader` 就会自动装配到需要 `ResourceLoader` 类型的字段、构造函数参数或方法参数中。有关更多信息，请参阅使用@Autowired。

要为包含通配符或使用特殊`classpath*:`资源前缀的资源路径加载一个或多个 Resource 对象，请考虑将 `ResourcePatternResolver` 实例（而不是 ResourceLoader）自动装配到应用程序组件中。


---

# 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://doc.shiker.tech/spring-he-xin-gong-neng/2.-resources/2.6.-resourceloaderaware-jie-kou.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.
