Spring中资源的加载ResourceLoader

Spring中资源的加载是定义在ResourceLoader接口中的,它跟前面提到的抽象资源的关系如下:
在这里插入图片描述
ResourceLoader的源码

public interface ResourceLoader {
     
  
    /** Pseudo URL prefix for loading from the class path: "classpath:" */  
    String CLASSPATH_URL_PREFIX = ResourceUtils.CLASSPATH_URL_PREFIX;  
      
    Resource getResource(String location);  
  
    ClassLoader getClassLoader();  
  
}  

我们发现,其实ResourceLoader接口只提供了classpath前缀的支持。而classpath*的前缀支持是在它的子接口ResourcePatternResolver中。

public interface ResourcePatternResolver extends ResourceLoader {
     
  
    /** 
     * Pseudo URL prefix for all matching resources from the class path: "classpath*:" 
     * This differs from ResourceLoader's classpath URL prefix in that it 
     * retrieves all matching resources for a given name (e.g. "/beans.xml"), 
     * for example in the root of all deployed JAR files. 
     * @see org.springframework.core.io.ResourceLoader#CLASSPATH_URL_PREFIX 
     */  
    String CLASSPATH_ALL_URL_PREFIX = "classpath*:";  
  
      
    Resource[] getResources(String locationPattern) throws IOException;  
  
}  

通过2个接口的源码对比,我们发现ResourceLoader提供 classpath下单资源文件的载入,而ResourcePatternResolver提供了多资源文件的载入。
ResourcePatternResolver有一个实现类:PathMatchingResourcePatternResolver,那我们直奔主题,查看PathMatchingResourcePatternResolver的getResources()

public Resource[] getResources(String locationPattern) throws IOException {
     
        Assert.notNull(locationPattern, "Location pattern must not be null");  
        //是否以classpath*开头  
        if (locationPattern.startsWith(CLASSPATH_ALL_URL_PREFIX)) {
     
            //是否包含?或者*  
            if (getPathMatcher().isPattern(locationPattern.substring(CLASSPATH_ALL_URL_PREFIX.length()))) {
     
                // a class path resource pattern  
                return findPathMatchingResources(locationPattern);  
            }  
            else {
     
                // all class path resources with the given name  
                return findAllClassPathResources(locationPattern.substring(CLASSPATH_ALL_URL_PREFIX.length()));  
            }  
        }  
        else {
     
            // Only look for a pattern after a prefix here  
            // (to not get fooled by a pattern symbol in a strange prefix).  
            int prefixEnd = locationPattern.indexOf(":") 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值