上文讲了 【Spring | 资源处理 】
本文讲一下resource的扩展接口相关
ResourceLoader 接口
ResourceLoader
接口用于加载 Resource
对象。
定义
定义如下:
public interface ResourceLoader {
Resource getResource(String location);
ClassLoader getClassLoader();
}
Spring 中,所有的 ApplicationContext
都实现了 ResourceLoader
接口。因此,所有 ApplicationContext
都可以通过 getResource()
方法获取 Resource
实例。
图解
图解如下:
![在这里插入图片描述](https://img-blog.csdnimg.cn/765873d04fb643faab18af9e385ed283.png)
示例
示例如下:
//
Resource template = ctx.getResource("some/resource/path/myTemplate.txt");
//
Resource template = ctx.getResource("classpath:some/resource/path/myTemplate.txt");
//
Resource template = ctx.getResource("file:///some/resource/path/myTemplate.txt");
//
Resource template = ctx.getResource("https://myhost.com/resource/path/myTemplate.txt");
策略
Spring根据各种位置路径加载资源的策略如下:
字首 |
样例 |
描述 |
classpath: |
classpath:com/myapp/config.xml |
从类路径加载 |
file: |
file:///data/config.xml |
以URL形式从文件系统加载 |
http: |
http://myserver/logo.png |
以URL形式加载 |
– |
/data/config.xml |
取决于底层ApplicationContext
|
ResourcePatternResolver接口
ResourcePatternResolver
接口是 ResourceLoader
接口的扩展,它的作用是定义策略,根据位置模式解析Resource
对象。
public interface ResourcePatternResolver extends ResourceLoader {
String CLASSPATH_ALL_URL_PREFIX = "classpath*:";
Resource[] getResources(String locationPattern) throws IOException;
}
由上文示例可知,该接口还为类路径中的所有匹配资源定义了一个特殊的classpath*:resource
前缀。请注意,在这种情况下,资源位置应该是一个没有占位符的路径 — 例如,类路径中的classpath*:/config/beans.xml
.JAR文件或不同目录可以包含多个具有相同路径和相同名称的文件。
PathMatchingResourcePatternResolver
是一个独立的实现,可以在ApplicationContext
外部使用,也可以被ResourceArrayPropertyEditor
用于填充Resource[]bean
属性。PathMatchingResourcePatternResolver
能够将指定的资源位置路径解析为一个或多个匹配的Resource
对象。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)