org.springframework.core.io.Resource
定义了资源的基本操作,例如是否可读、是否存在等。
public interface Resource extends InputStreamSource {...}
public interface InputStreamSource {
InputStream getInputStream() throws IOException;
}
类关系图如下
这里使用的是策略模式,Resource是主接口,其三个实现类是策略。
EncodedResource 对资源进行编码。
ServletContextResource 访问web容器上下文的资源,以流和URL的形式进行访问,还可以从war包中访问资源。
FileSystem 实现了WitableResource接口可以进行资源的写操作。
根据资源地址自动选择正确的Resource,强大的加载资源的方式:
- 自动识别“classpath:”、“file:”等资源地址前缀
- 支持自动解析Ant风格带通配符的资源地址,用于匹配URI
Ant路径匹配表达式:
- ?匹配任何单字符
- *匹配0或者任意数量的字符
- ** 匹配0或更多的目录
在DefaultResourceLoader中,获取Resource的具体实现类实例:
@Override
public Resource getResource(String location) {
Assert.notNull(location, "Location must not be null");
// 用户自定义协议资源解决策略
for (ProtocolResolver protocolResolver : getProtocolResolvers()) {
Resource resource = protocolResolver.resolve(location, this);
if (resource != null) {
return resource;
}
}
if (location.startsWith("/")) {
return getResourceByPath(location);
}
// 常量定义在org.springframework.util.ResourceUtils
else if (location.startsWith("classpath:")) {
return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
}
else {
try {
// Try to parse the location as a URL...
URL url = new URL(location);
return (ResourceUtils.isFileURL(url) ? new FileUrlResource(url) : new UrlResource(url));
}
catch (MalformedURLException ex) {
// No URL -> resolve as resource path.
return getResourceByPath(location);
}
}
}
protected Resource getResourceByPath(String path) {
return new ClassPathContextResource(path, getClassLoader());
}
ResourceLoader类关系图
ResourcePatternResolver 加持了ResourceLoader缺少的按路径匹配返回多个Resource实例的方法,
public interface ResourcePatternResolver extends ResourceLoader {
String CLASSPATH_ALL_URL_PREFIX = "classpath*:";
Resource[] getResources(String locationPattern) throws IOException;
}
ApplicationContext这个熟悉的面孔也继承了ResourcePatternResolver接口,也就是说所有的ApplicationContext的实现类都可以看做是ResourceLoader的实现类。
public interface ApplicationContext extends EnvironmentCapable, ListableBeanFactory, HierarchicalBeanFactory,
MessageSource, ApplicationEventPublisher, ResourcePatternResolver {...}