java
public class DefaultResourceLoader implements ResourceLoader {
public static final String CLASSPATH_URL_PREFIX = "classpath:";
@Override
public Resource getResource(String location) {
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)) { // 如果"classpath"开头,则最终还是类加载器处理
return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
}else {
try {
// http协议:加载本地文件或者外部资源,
URL url = new URL(location);
return (ResourceUtils.isFileURL(url) ? new FileUrlResource(url) : new UrlResource(url));
}
catch (MalformedURLException ex) {
// 还是类加载器处理
return getResourceByPath(location);
}
}
}
}
判断是否为文件:查看url协议是否file or vfsfile or vfs,否则直接返回UrlResource。
UrlResource处理对象为外部资源,即网站、图片等协议为Http的外部资源【例如,无法处理jar包】。底层是JDK完成对资源的远程获取。