4.4 ResourceLoader 接口
ResourceLoader 接口是用来加载Resource 对象的,换句话说,就是当一个对象需要获取 Resource 实例时,可以选择实现ResourceLoader 接口。
public interface ResourceLoader {
Resource getResource(String location);
}
spring 里所有的应用上下文都是实现了 ResourceLoader 接口,因此,所有应用上下文都可以通过getResource() 方法获取 Resource 实例。
当你在指定应用上下文调用 getResource()方法时,而指定的位置路径又没有包含特定的前缀,spring 会根据当前应用上下文来决定返回哪一种类型 Resource。举个例子,假设下面的代码片段是通过ClassPathXmlApplicationContext 实例来调用的:
Resource template = ctx.getResource("some/resource/path/myTemplate.txt");
那 spring 会返回一个ClassPathResource对象;类似的,如果是通过一个 FileSystemXmlApplicationContext实例调用的,返回的是一个 FileSystemResource 对象;如果是通过 WebApplicationContext 实例调用的,返回的是一个 ServletContextResource对象……
如上所说,你就可以在指定的应用上下中使用 Resource 实例来加载当前应用上下文的资源。
还有另外一种场景里,如在其他应用上下文里,你可能会强制需要获取一个 ClassPathResource对象,这个时候,你可以通过加上指定的前缀来实现这一需求,如:
Resource template = ctx.getResource("classpath:some/resource/path/myTemplate.txt");
类似的,你可以通过其他任意的 url 前缀来强制获取 UrlResource对象:
Resource template = ctx.getResource("file:///some/resource/path/myTemplate.txt");
Resource template = ctx.getResource("http://myhost.com/resource/path/myTemplate.txt");
下面,给出一个表格来总结一下 spring 根据各种位置路径加载资源的策略:
Table 4.1. Resource strings
| 前缀 | 样例 | 说明 |
|---|---|---|
| classpath: | classpath:com/myapp/config.xml |
从类路径加载 |
| file: | file:///data/config.xml |
将其作为 URL 对象,从文件系统加载 [1]] |
| http: | http://myserver/logo.png |
将其作为 URL 对象 加载 |
| (none) | /data/config.xml |
取决于底层的 ApplicationContext |
| [1] 另请参阅:[Section 4.7.3, “FileSystemResource 警告” |