Spring源码 - Resource、ResourceLoader

本文详细介绍了Spring中Resource接口及其策略模式的实现,如EncodedResource、ServletContextResource和FileSystemResource。ResourceLoader和ResourcePatternResolver进一步扩展了资源处理能力,支持Ant路径匹配和多种协议的资源定位。ApplicationContext作为ResourcePatternResolver的实现,可在应用上下文中方便地加载资源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Resource
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 {...}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值