整体认识
面对这个类,名字就是默认的资源加载器,器实现了ResourceLoad接口。ResourceLoad接口指定了基础资源加载规范,这个接口很简单
public interface ResourceLoader {
/** Pseudo URL prefix for loading from the class path: "classpath:". */
String CLASSPATH_URL_PREFIX = ResourceUtils.CLASSPATH_URL_PREFIX;
Resource getResource(String location);
@Nullable
ClassLoader getClassLoader();
ResourceLoad接口中最重要的的就是类加载器,资源地址表达形式:
-
classpath:前缀开头的表达式,例如: classpath:smart-context.xml
-
“/”开头的表达式,例如:/WEB-INF/classes/smart-context.xml
-
非“/”开头的表达,例如:WEB-INF/classes/smart-context.xml
-
url协议,例如:file:/D:/ALANWANG-AIA/Horse-workspace/chapter3/target/classes/smart-context.xml
回到DefaultResourceLoader类中,其中通过addProtocolResolver(ProtocolResolver resolver)方法来注册资源解析器,解析其他协议。
其中执行文件加载的方法就是getResource(String location)方法
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);
}
else if (location.startsWith(CLASSPATH_URL_PREFIX)) {
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);
}
}
}
总结
该类是在阅读Spring IOC源码是,需要解析配置文件才接触到的,该类也就是辅助工具类,从类名也能清楚的知道该类的功能,因为我的重点不在此,也就不对该类进行进一步分析,往后有需要在丰富此篇文章。