ResourceLoader原理

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完成对资源的远程获取。

相关推荐
萧瑟余晖25 分钟前
JDK 26 新特性详解
java·开发语言
马优晨1 小时前
Freemarker 完整讲解(后端 Java 模板引擎)
java·开发语言·freemarker·freemarker 完整讲解·freemarker模板引擎
维天说4 小时前
CLI-Switch 2026年3月版历史设计:Hook、TTY 隔离与 JSON 状态
java·服务器·json
Zane19944 小时前
并发 vs 并行:别再傻傻分不清了,一文讲透 Java 并发编程的第一课
java·后端
噢,我明白了5 小时前
java中Excel的导入和导出(EasyExcel)
java·开发语言·excel
吠品5 小时前
Zabbix Web界面误报Server未运行的排查与解决
java·服务器·数据库
啊湘5 小时前
天气查询API接口 按月Token鉴权 实时天气 物联网可用 文档齐全
java·后端·struts
Java内核笔记6 小时前
告别十亿美元的错误 : Spring Boot 4 空安全 (JSpecify) 实战
java·spring boot·后端
糖果店的幽灵6 小时前
langgraph的 MessagesState 解读
java·开发语言·人工智能·windows·langgraph
极光代码工作室7 小时前
基于SpringBoot的在线博客系统
java·springboot·web开发·后端开发