JAVA全系列 教程
3762个小节阅读:7092.9k
目录
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
ResourceLoader 接口是Spring框架提供的资源加载器。通过这个接口加载资源,根据加载方式,获取到Resources接口的哪个实现类。在ApplicationContext接口的实现类中都实现类ResourceLoader,所以ApplicationContext不同实现类对应使用不同的Resources实现类。
ResourceLoader接口的内容也比较简单。
xxxxxxxxxx
public interface ResourceLoader {
// 常量值为 classpath:
String CLASSPATH_URL_PREFIX = ResourceUtils.CLASSPATH_URL_PREFIX;
// 加载资源,返回资源对象。不同的加载方式返回不同的资源对象
Resource getResource(String location);
// 获取类加载器
@Nullable
ClassLoader getClassLoader();
}
特点如下:
前缀 | Resources类型 | ApplicationContext实现类 |
---|---|---|
classpath: | ClassPathResource | ClassPathXmlApplicationContext 或其他实现类以classpath:开头 |
无前缀 | FileSystemResource | FileSystemXmlApplicationContext |
无前缀 | ServletContextResource | WebApplicationContext |
file:///或https: | UrlResource | 无论哪个实现类,只要有这些前缀 |
无前缀 | 根据ApplicationContext实现类判断 |
通过上面表格也说明了,我们之前一直使用的ClassPathXmlApplicationContext使用的是ClassPathResource进行资源加载。
所以下面几种写法是等效的,都是使用ClassPathResource进行资源加载。
没有前缀
xxxxxxxxxx
ApplicationContext ac = new ClassPathXmlApplicationContext("ac.xml");
有前缀
xxxxxxxxxx
ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:ac.xml");
使用ApplicationContext其他实现类,但是路径以classpath:前缀开头
xxxxxxxxxx
ApplicationContext ac = new FileSystemXmlApplicationContext("classpath:ac.xml");
System.out.println(ac.getResource("classpath:ac.xml").getClass().getName());