zoukankan      html  css  js  c++  java
  • 《Spring》(十) ---- ApplicationContext之统一资源加载策略

      Spring的resource

      Spring框架内部使用Resource接口作为所有资源的抽象和接口。例如: 

    BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("..."));

      ClassPathResource就是Resource的一个特定类型的实现,代表的实位于Classpath中的资源。

      Resource接口可以根据资源的不同类型,或者资源所处的不同场合,给出相应的具体实现:

        a. ByteArrayResource  将字节(byte)数组提供的数据作为一种资源进行封装

        b. ClassPathResource  该实现从Java应用程序的ClassPath中加载具体资源并进行封装

        c. FileSystemResource  对java.io.File类型的封装,所以,我们可以以文件或者URL的形式对该类型资源进行访问,只要能跟File打的交道,基本上跟FileSystemResource也可以.

        d. UrlResource  通过java.net.URL进行的具体资源查找定位的实现类

      如果以上资源还不能满足要求,可以根据相应场景给出自己的实现,只需实现Resource接口就是。

      ResourceLoader

      ResourceLoader的职责就是查找和定位资源。具体的资源查找定位策略由相应的ResourceLoader实现类给出。ResourceLoder定义如下:

    public interface ResourceLoader {
        String CLASSPATH_URL_PREFIX = ResourceUtils.CLASSPATH_URL_PREFIX;
        Resource getResource(String location);
        ClassLoader getClassLoader();
    }

      批量查找的ResourceLoader ---- ResourcePatternResolver

      ResourcePatternResolver则可以根据指定的资源路径匹配模式,每次返回多个Resource实例

      定义如下: 

    public interface ResourcePatternResolver extends ResourceLoader {
        String CLASSPATH_ALL_URL_PREFIX = "classpath*:";
        Resource[] getResources(String locationPattern) throws IOException;
    }

    Resourcehe 和 ResourceLoader的层次图(摘自 http://www.jianshu.com/p/9cdd6d750216):

      

      ApplicationContext和ResourceLoader

      再回顾一下BeanFactory和ApplicationContext继承关系图: 

      ApplicationContext继承了ResourcePatternResolver,当然就间接实现了ResourceLoader接口。所以,然和的ApplicationContext实现都可以看作是一个ResourceLoader甚至是ResourcePatternResolver。而这就是ApplicationContext支持Spring内统一资源加载策略的真相。

      通常,所有的ApplicationContext实现类会直接或间接地继承AbstractApplicationContext,从下图可以看出ApplicationContext与ResourceLoader的所有关系

     所以AbstractApplication可以作为ResourceLoader和ResourcePatternResolver来使用。

  • 相关阅读:
    IDEA启动tomcat时提示:...init The APR based Apache Tomcat Native library failed to load. The error reported was ...tcnative-1.dll: Can't load IA 32-bit .dll on a AMD 64-bit platform
    Mysql中(增加、删除字段,修改字段名、字段类型、注释,调整字段顺序等)常用操作
    MySql、Mariadb创建数据库、用户及授权
    三款大前端UI框架
    TubeMQ
    Delphi 修改系统时间格式为:'yyyy-MM-dd HH:mm:ss', 'yyyy''年''M''月 ''d''日'''
    QString与LPCWSTR 带中文的相互转换
    Windows 下搭建 Apache Http Server 文件系统(详细)
    Django day32 跨域问题,创建vue项目,axios的使用
    Django day31 contentType组件,Django的缓存
  • 原文地址:https://www.cnblogs.com/IvySue/p/6485297.html
Copyright © 2011-2022 走看看