06.Spring 资源加载 - ResourceLoader

基本概念

ResourceLoader 接口,在 Spring 中用于加载资源,通过它可以获取一个 Resouce 对象。


内部构造

首先来看它的接口定义:

public interface ResourceLoader {

    // 从 classpath 加载资源时的前缀
    String CLASSPATH_URL_PREFIX = ResourceUtils.CLASSPATH_URL_PREFIX;

    // 关键-> 取得 Resource 对象,即获取资源
    Resource getResource(String location);

    ClassLoader getClassLoader();
}

再来看它的继承关系,如下所示:

这里写图片描述

  • DefaultResourceLoader : 作为 ResourceLoader 接口的直接实现类,该类实现了基本的资源加载功能,可以实现对单个资源的加载。

  • ResourcePatternResolver :该接口继承了 ResourceLoader,定义了加载多个资源的方法, 可以实现对多个资源的加载。


DefaultResourceLoader

上面介绍过该类通过实现 ResourceLoader 接口实现了加载单个资源的功能。它的子类通过继承它来实现具体的资源访问策略。下面来探究下该类如何加载单个资源:

public Resource getResource(String location) {
    Assert.notNull(location, "Location must not be null");

    // ① 是否以"/" 开头
    if (location.startsWith("/")) {
        return getResourceByPath(location);
    }
    // ② 是否以"classpath:" 开头,若是则表示该资源类型为 ClassPathResource
    else if (location.startsWith(CLASSPATH_URL_PREFIX)) {
        return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
    }
    else {
        try {
            // ③若都不是,则当成 UrlResource 来处理
            URL url = new URL(location);
            return new UrlResource(url);
        }catch (MalformedURLException ex) {
            // 若不是 UrlResource,则仍当作 ① 情况来处理 
            return getResourceByPath(location);
        }
    }
}

观察代码,发现在拿到资源的路径 loaction 后,会根据 location 的形式分成三种情况来处理:

  • 以 “/” 开头:默认调用类中的 getResourceByPath 方法处理。它的子类通过重写该方法实现不同形式的资源的访问。

  • 以 “classpath:” 开头:当成 ClassPathResource 资源对待。

  • 其他情况: 当成 UrlResource 资源对待,如果访问资源抛出异常,则调用 getResourceByPath 来完成资源的访问。


ResourcePatternResolver

该接口继承自 ResourceLoader 接口,在其基础上增加了同时对多个资源的访问。首先来看它的接口定义:

public interface ResourcePatternResolver extends ResourceLoader {

    String CLASSPATH_ALL_URL_PREFIX = "classpath*:";

    // 例如使用 ant 风格的路径,匹配路径下的多个资源
    Resource[] getResources(String locationPattern) throws IOException;
}

1.PathMatchingResourcePatternResolver

该类是 ResourcePatternResolver 接口的直接实现类,它是基于模式匹配的,默认使用AntPathMatcher 进行路径匹配,它除了支持 ResourceLoader 支持的前缀外,还额外支持 “classpath*” ,下面来探究下该类是如何实现对多个资源的访问。

public Resource[] getResources(String locationPattern) throws IOException {

    Assert.notNull(locationPattern, "Location pattern must not be null");

    // 是否以 "classpath*:" 开头 
    if (locationPattern.startsWith(CLASSPATH_ALL_URL_PREFIX)) {

        // 通过 getPathMatcher 方法取得 PathMatcher ,默认只有 AntPathMatcher 一个实现类
        // 通过 isPattern 方法判断 "classpath*:" 之后的路径是否包含 "*" 或 "?"
        if (getPathMatcher().isPattern(locationPattern.substring(CLASSPATH_ALL_URL_PREFIX.length()))) {

            // 关键 -> 找到所有匹配路径(ant 风格)的资源
            return findPathMatchingResources(locationPattern);

        }else {
            // 关键 -> 通过类加载器查找
            return findAllClassPathResources(locationPattern.substring(CLASSPATH_ALL_URL_PREFIX.length()));
        }
    }else {

        int prefixEnd = locationPattern.indexOf(":") + 1;

        // 判断资源路径 ":" 之后的部分是否包含 "*" 或 "?"
        if (getPathMatcher().isPattern(locationPattern.substring(prefixEnd))) {
            return findPathMatchingResources(locationPattern);
        }else {
            // 若不存在表示是单个资源,则通过从构造函数传入的 ResourceLoader 取得
            return new Resource[] {getResourceLoader().getResource(locationPattern)};
        }
    }
}

观察代码:

  • 该方法首先会去判断资源路径是否是类路径下的资源(以 “classpath*:” 开头),然后再去判断路径是否允许存在多个匹配的资源(路径中包含 “*” 或 “?”)。

  • 只要资源路径允许多个匹配的资源,就会通过 findPathMatchingResources 方法寻找所有的匹配资源;

  • 若资源路径只存在单个匹配,则通过类加载器寻找类路径下的资源(findAllClassPathResources) ,其他资源则通过 ResourceLoader 的 getResource 方法获取。


2.ApplicationContext

通过上面的继承关系图可知,该接口继承了 ResourcePatternResolver 接口,说明它也集成了对对单个或多个资源的访问功能。

当 Spring 需要进行资源访问时,实际上并不需要直接使用 Resource 实现类,而是调用 getResource 方法来获取资源。

当通过 ApplicationContext 实例获取 Resource 实例时,它将会负责选择具体的 Resource 的实现类。代码如下:

//通过 ApplicationContext访问资源
 Resource res = ctx.getResource("some/resource/path/myTemplate.txt);

从上面代码中无法确定 Spring 将哪个实现类来访问指定资源,Spring 将采用和 ApplicationContext 相同的策略来访问资源。也就是说:如果 ApplicationContext 是 FileSystemXmlApplicationContext,res 就是 FileSystemResource 实例;如果 ApplicationContext 是 ClassPathXmlApplicationContext,res 就是 ClassPathResource 实例;如果 ApplicationContext 是 XmlWebApplicationContext,res 是 ServletContextResource 实例。

也就是说 ApplicationContext 将会确定具体的资源访问策略,从而将应用程序和具体的资源访问策略分离开来,这就体现了策略模式的优势。


参考

Spring框架中,ResourceLoader是一个用于加载资源的接口。它提供了一种统一的方式来加载各种类型的资源文件,比如类路径上的文件、文件系统中的文件、URL资源等。 ResourceLoader接口定义了一个getResource(String location)方法,用于获取资源对象。具体的实现类包括ClassPathResourceLoader、FileSystemResourceLoader和UrlResourceLoader等。 使用ResourceLoader可以方便地加载资源文件,并且可以处理多种类型的资源路径。下面是一个示例代码,演示如何使用ResourceLoader加载资源文件: ```java import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; public class Main { private ResourceLoader resourceLoader; public Main(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } public void loadResource(String location) { Resource resource = resourceLoader.getResource(location); // 使用resource对象进行操作,比如读取内容等 } public static void main(String[] args) { // 创建Spring容器并获取ResourceLoader实例 ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); ResourceLoader resourceLoader = context; // 使用ResourceLoader加载资源文件 Main main = new Main(resourceLoader); main.loadResource("classpath:config.properties"); } } ``` 在上述示例中,我们通过Spring容器获取了一个ResourceLoader实例,然后调用它的getResource方法来加载资源文件。可以通过不同的前缀来指定不同的资源类型,比如"classpath:"表示类路径上的资源文件。 使用SpringResourceLoader可以更灵活地处理资源加载,并且可以适应不同的资源路径。它是Spring框架中用于加载资源的重要组件之一。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

oxf

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值