Spring扩展(3)-资源加载

1.Resource

Resource接口可以根据资源的不同类型,或者资源所处的不同场合,给出相应的具体实现;
Spring中提供了以下一些实现类:


image.png

Resource接口定义了11个方法,可以帮助我们查询资源状态、访问资源内容,甚至根据当前资源创建新的相对资源。不过,要真想实现自定义的Resource,倒是真没必要直接实现该接口,我们可以继承AbstractResource抽象类,然后根据当前具体资源特征,覆盖相应的方法就可以了。

2.ResourceLoader

  • ResourceLoader主要用来去查找和定位这些资源,其实就是主要通过Resource#getResource方法,通过它,我们就可以根据指定的资源位置,定位到具体的资源实例;
    ResourceLoader有一个默认的实现类,即DefaultResourceLoader,该类默认的资源查找处理逻辑如下,同时还有FileSystemResourceLoader,ClassRelativeResourceLoader,这些类的目的是为了扩展DefaultResourceLoader,处理一些DefaultResourceLoader处理不到的场景,当然,这样也给我们参考去实现自己特殊场景下自定义实现:
 public Resource getResource(String location) {
        Assert.notNull(location, "Location must not be null");
        for (ProtocolResolver protocolResolver : this.protocolResolvers) {
            Resource resource = protocolResolver.resolve(location, this);
            if (resource != null) {
                return resource;
            }
        }
        //1.判断是否以"/"打头,是则委派getResourceByPath(String)方法来定位
        if (location.startsWith("/")) {
            return getResourceByPath(location);
        }
        //2.检查资源路径是否以classpath:前缀打头,是则尝试构造ClassPathResource类 型资源并返回
        else if (location.startsWith(CLASSPATH_URL_PREFIX)) {
            return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
        }
        else {
            try {
                //3.通过URL资源路径来定位资源,如果没有抛出MalformedURLException, 有则会构造UrlResource类型的资源并返回
                URL url = new URL(location);
                return new UrlResource(url);
            }catch (MalformedURLException ex) {
                return getResourceByPath(location);
            }
        }
    }
  • 关于DefaultResourceLoader的使用
    借助其内部的getResource操作,我们可以这样做:
@Test
public void testResourceTypesWithFileSystemResourceLoader() {
    ResourceLoader resourceLoader = new FileSystemResourceLoader();
    Resource fileResource = resourceLoader.getResource(path);
    log.info("{}", fileResource instanceof FileSystemResource);
    log.info("{}", fileResource.exists());
    Resource urlResource = resourceLoader.getResource("file:" + path);
    log.info("{}", urlResource instanceof UrlResource);
}
  • ResourcePatternResolver(多个ResourceLoader)
    ResourcePatternResolver是ResourceLoader的扩展,ResourceLoader每次只能根据资源路径 返回确定的单个Resource实例,而ResourcePatternResolver则可以根据指定的资源路径匹配模式, 每次返回多个Resource实例;
public interface ResourcePatternResolver extends ResourceLoader {
    String CLASSPATH_ALL_URL_PREFIX = "classpath*:";
    Resource[] getResources(String var1) throws IOException;
}

ResourcePatternResolver在ResourceLoader原有定义的基础上,新增了getResources方法定义,以支持根据路径匹配模式返回多个Resources的功能。它同时还引入了一种新的协议前缀classpath*:,针对这一点的支持,将由相应的子类实现给出,这里我会分析PathMatchingResourcePatternResolver的相关实现;

 //1.构造函数可指定传入classLoader,作为resourceLoader的实现
 public PathMatchingResourcePatternResolver(ClassLoader classLoader) {
    this.resourceLoader = new DefaultResourceLoader(classLoader);
 }

 //2.支持Ant风格的路径匹配模式,
 private PathMatcher pathMatcher = new AntPathMatcher();
 public void setPathMatcher(PathMatcher pathMatcher) {
    Assert.notNull(pathMatcher, "PathMatcher must not be null");
    this.pathMatcher = pathMatcher;
 }

 //3.如果不符合ant风格的格式,其在加载资源的行为上会与DefaultResourceLoader基本相同, 只存在返回的Resource数量上不同;
 public Resource[] getResources(String locationPattern) throws IOException {
    Assert.notNull(locationPattern, "Location pattern must not be null");
    if (locationPattern.startsWith(CLASSPATH_ALL_URL_PREFIX)) {
        if (getPathMatcher().isPattern(locationPattern.substring(CLASSPATH_ALL_URL_PREFIX.length()))) {
            return findPathMatchingResources(locationPattern);
        }
        else {
            return findAllClassPathResources(locationPattern.substring(CLASSPATH_ALL_URL_PREFIX.length()));
        }
    }
    else {
        int prefixEnd = (locationPattern.startsWith("war:") ? locationPattern.indexOf("*/") + 1 :
                locationPattern.indexOf(":") + 1);
        if (getPathMatcher().isPattern(locationPattern.substring(prefixEnd))) {
            return findPathMatchingResources(locationPattern);
        }
        else {
            return new Resource[] {getResourceLoader().getResource(locationPattern)};
        }
    }
}

关于其使用,默认使用的是DefaultResourceLoader,但我们可以手动改变ResourceLoader:

@Test
public void testPathMatchingResourcePatternResolver() {
    ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
    Resource fileResource = resourceResolver.getResource(path);
    log.info("{}", fileResource instanceof ClassPathResource);
    log.info("{}", fileResource.exists());
    resourceResolver = new PathMatchingResourcePatternResolver(new FileSystemResourceLoader());
    fileResource = resourceResolver.getResource(path);
    log.info("{}", fileResource instanceof FileSystemResource);
    log.info("{}", fileResource.exists());
}

3.ApplicationContext

此时此刻,对Spring内部的资源加载应该已经很清晰了,但是你是否发现,在spring的内部,其实都是ApplicationContext这个东西在作怪哦!接下来,我将讲述下ApplicationContext是怎么做到资源统一加载的;

public interface ApplicationContext extends EnvironmentCapable, ListableBeanFactory, HierarchicalBeanFactory,MessageSource,ApplicationEventPublisher, ResourcePatternResolver{
        ....
} 

看类继承关系,你有没有看到ResourcePatternResolver,这个玩意就是ApplicationContext支持spring统一资源加载的真相;ApplicationContext实现类是AbstractApplicationContext,再看它的实现:

public abstract class AbstractApplicationContext extends DefaultResourceLoader
    implements ConfigurableApplicationContext, DisposableBean {

    /** ResourcePatternResolver used by this context */
    private ResourcePatternResolver resourcePatternResolver;

    public AbstractApplicationContext() {
        this.resourcePatternResolver = getResourcePatternResolver();
    }

    protected ResourcePatternResolver getResourcePatternResolver() {
        return new PathMatchingResourcePatternResolver(this);
    }
        ...
}

AbstractApplicationContext继承了DefaultResourceLoader,所以啊,它的getResource方法当然就直接用DefaultResourceLoader的了,而getResources则用的其内部声明的resourcePatternResolver,对应的实例类型为PathMatchingResourcePatternResolver,之前说过,PathMatchingResourcePatternResolver构造的时候会接受一个ResourceLoader,而AbstractApplicationContext本身又继承自DefaultResourceLoader,自然把this传入即可啦;
总结下:

  • ApplicationContext的实现类在作为ResourceLoader或者ResourcePatternResolver时候的行为,完全就是委派给了PathMatchingResourcePatternResolver和DefaultResourceLoader来做!
    所以,我们其实还可以这么使用:
@Test
public void testApplicationContext() {
    //以ResourceLoader的方式使用
    ResourceLoader resourceLoader = new ClassPathXmlApplicationContext(configurePath);
    // 或者
    //ResourceLoader resourceLoader = new FileSystemXmlApplicationContext(configurePath);
    Resource fileResource = resourceLoader.getResource(path);
    log.info("{}", fileResource instanceof ClassPathResource);
    log.info("{}", fileResource.exists());
    Resource urlResource2 = resourceLoader.getResource("http://www.spring21.cn");
    log.info("{}", urlResource2 instanceof UrlResource);
}
  • 那么关于ResourceLoader类型的注入,从前我们都是通过属性注入或者setter注入时是这么玩的;
public class FooBar{
    private ResourceLoader resourceLoader;

    public void foo(String location) {
      System.out.println(getResourceLoader().getResource(location).getClass());
    }

    public ResourceLoader getResourceLoader() { return resourceLoader;}

    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;   
    }
}

然后这么配置:

<bean id="resourceLoader" class="org.springframework.core.io.DefaultResourceLoader"> </bean>
<bean id="fooBar" class="...FooBar"> 
    <property name="resourceLoader">
        <ref bean="resourceLoader"/> 
    </property>
</bean>

然而ApplicationContext容器本身就是一个ResourceLoader,我们为了该类还需要单独提供一个resourceLoader实例就有些多于了,直接将当前的ApplicationContext容器作为ResourceLoader注入不就行了? 而ResourceLoaderAware和ApplicationContextAware接口都帮助我们做到这一点!这时候代码应该这么写了;

public class FooBar implements ResourceLoaderAware{
    private ResourceLoader resourceLoader;

    public void foo(String location){
        System.out.println(getResourceLoader().getResource(location).getClass());
    }

    public ResourceLoader getResourceLoader() {
        return resourceLoader;
    }

    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }
}

or 这么写:

public class FooBar implements ApplicationContextAware{
    private ResourceLoader resourceLoader;

    public void foo(String location){
        System.out.println(getResourceLoader().getResource(location).getClass());
    }

    public ResourceLoader getResourceLoader() {
        return resourceLoader;
    }

    public void setApplicationContext(ApplicationContext ctx) throws BeansException {
        this.resourceLoader = ctx;
    }
}

这时候的配置文件该这么描述,多么清爽啊!:

<bean id="fooBar" class="...FooBar" />

容器启动的时候,就会自动将当前ApplicationContext容器本身 注入到FooBar中,因为ApplicationContext类型容器可以自动识别Aware接口,

ok! 写了一大堆,应该描述清楚了吧,谨以此文献给最近悠闲的自己,多学习,多动手,多做总结!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,635评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,628评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,971评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,986评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,006评论 6 394
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,784评论 1 307
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,475评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,364评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,860评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,008评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,152评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,829评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,490评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,035评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,156评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,428评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,127评论 2 356