Spring源码之Resource加载源码解析(一)

Spring中资源处理架构

这里写图片描述
接口解析:
1. InputStreamSource: 支持对获取InputStreamSource流的扩展接口。
2. Resource: 用于从实际资源类型抽象出来的资源’描述’的接口
3. WritableResource :支持对其进行写入的资源的扩展接口。
4. ContextResource:从一个封闭的“上下文‘加载一个资源的扩展接口
抽象类解析:
1. AbstractResource 实现了基础的资源操作的抽象类
2. AbstractFileResolvingResource 抽象了对File资源操作的抽象类
各个类分工:
1. FileSystemResource:以文件的绝对路径方式进行访问,用来获取文件系统里面的资源。
2. ClassPathResourcee:以类路径的方式访问,可用来获取类路径下的资源文件。
3. UrlResource:以URL的方式访问,可用来代表URL对应的资源,它对URL做了一个简单的封装
4. ByteArrayResource:是针对于字节数组封装的资源,它的构建需要一个字节数组。
5. InputStreamResource:是针对于输入流封装的资源,它的构建需要一个输入流。
6. ServletContextResource:是针对于ServletContext封装的资源,用于访问ServletContext环境下的资源。ServletContextResource持有一个ServletContext的引用,其底层是通过ServletContext的getResource()方法和getResourceAsStream()方法来获取资源的。
7. VfsResource:对VFS资源的封装,提供对VFS资源访问及操作,内部则是调用VfsUtils实现的。
tip:vfs是Virtual File System虚拟文件系统,也称为虚拟文件系统开关(Virtual Filesystem Switch).是Linux档案系统对外的接口。任何要使用档案系统的程序都必须经由这层接口来使用它。(摘自百度百科…)它能一致的访问物理文件系统、jar资源、zip资源、war资源等,VFS能把这些资源一致的映射到一个目录上,访问它们就像访问物理文件资源一样,而其实这些资源不存在于物理文件系统。
8. DescriptiveResource: 包含资源的描述,但不指向实际的资源。例如:当API需要一个资源resource作为参数,但不一定用于实际读取,只用作占位符。
9. BeanDefinitionResource: 每个bean实际上也是资源的资源,而BeanDefinitionResource则是一个beanDefinition资源的封装。

资源工具类ResourceUtils

用途:用于将资源位置解析为文件系统中的文件的实用方法。主要用于Spring框架内的内部使用。

/**
 * 该工具被下面这些类都用到啦,可以说很重要
 * @see org.springframework.core.io.Resource
 * @see org.springframework.core.io.ClassPathResource
 * @see org.springframework.core.io.FileSystemResource
 * @see org.springframework.core.io.UrlResource
 * @see org.springframework.core.io.ResourceLoader
 **/
public abstract class ResourceUtils {

    //加载类路径前缀:“classpath:“
    public static final String CLASSPATH_URL_PREFIX = "classpath:";

    //从文件系统加载的URL前缀"file:"
    public static final String FILE_URL_PREFIX = "file:";

    //文件系统中文件的URL协议: "file"
    public static final String URL_PROTOCOL_FILE = "file";

    /** URL protocol for an entry from a jar file: "jar" */
    public static final String URL_PROTOCOL_JAR = "jar";

    /** URL protocol for an entry from a zip file: "zip" */
    public static final String URL_PROTOCOL_ZIP = "zip";

    /** URL protocol for an entry from a WebSphere jar file: "wsjar" */
    public static final String URL_PROTOCOL_WSJAR = "wsjar";

    /** URL protocol for an entry from a JBoss jar file: "vfszip" */
    public static final String URL_PROTOCOL_VFSZIP = "vfszip";

    /** URL protocol for a JBoss file system resource: "vfsfile" */
    public static final String URL_PROTOCOL_VFSFILE = "vfsfile";

    /** URL protocol for a general JBoss VFS resource: "vfs" */
    public static final String URL_PROTOCOL_VFS = "vfs";

    /** URL protocol for an entry from an OC4J jar file: "code-source" */
    public static final String URL_PROTOCOL_CODE_SOURCE = "code-source";

    //jar中的JAR URL和文件路径之间的分隔符
    public static final String JAR_URL_SEPARATOR = "!/";


    //返回给定资源的位置是一个网址:无论是一个特殊的“路径”伪URL或一个标准的URL。
    public static boolean isUrl(String resourceLocation) {

        if (resourceLocation == null) {
            return false;
        }
        //特殊的“路径”伪URL:'classpath:'
        if (resourceLocation.startsWith(CLASSPATH_URL_PREFIX)) {
            return true;
        }
        try {
            //一个标准的URL
            new URL(resourceLocation);
            return true;
        }
        catch (MalformedURLException ex) {
            return false;
        }
    }


    //获取给定“资源定位”的URL
    public static URL getURL(String resourceLocation) throws FileNotFoundException {
        //非空校验
        Assert.notNull(resourceLocation, "Resource location must not be null");
        //特殊的“路径”伪URL:'classpath:'
        if (resourceLocation.startsWith(CLASSPATH_URL_PREFIX)) {
            //截取classpath:后面的一段
            String path = resourceLocation.substring(CLASSPATH_URL_PREFIX.length());
            //获取当前类加载器
            ClassLoader cl = ClassUtils.getDefaultClassLoader();
            //使用不同的类加载加载的根目录是不同的
            URL url = (cl != null ? cl.getResource(path) : ClassLoader.getSystemResource(path));
            if (url == null) {
                String description = "class path resource [" + path + "]";
                throw new FileNotFoundException(
                        description + " cannot be resolved to URL because it does not exist");
            }
            return url;
        }
        try {
            // 直接尝试是否为“标准URL”
            return new URL(resourceLocation);
        }
        catch (MalformedURLException ex) {
            // no URL -> treat as file path
            try {
                //作为文件路径处理,再转换为URL
                return new File(resourceLocation).toURI().toURL();
            }
            catch (MalformedURLException ex2) {
                throw new FileNotFoundException("Resource location [" + resourceLocation +
                        "] is neither a URL not a well-formed file path");
            }
        }
    }


    //获取给定“资源定位”的File
    public static File getFile(String resourceLocation) throws FileNotFoundException {
        //非空校验
        Assert.notNull(resourceLocation, "Resource location must not be null");
        //特殊的“路径”伪URL:'classpath:'
        if (resourceLocation.startsWith(CLASSPATH_URL_PREFIX)) {
            //截取classpath:后面的一段
            String path = resourceLocation.substring(CLASSPATH_URL_PREFIX.length());
            //生成一段描述,用于抛错提示
            String description = "class path resource [" + path + "]";
            //获取当前类加载器
            ClassLoader cl = ClassUtils.getDefaultClassLoader();
            URL url = (cl != null ? cl.getResource(path) : ClassLoader.getSystemResource(path));
            if (url == null) {
                throw new FileNotFoundException(
                        description + " cannot be resolved to absolute file path " +
                        "because it does not reside in the file system");
            }
            //获取加载文件对象
            return getFile(url, description);
        }
        try {
            // 尝试利用URL获取File对象
            return getFile(new URL(resourceLocation));
        }
        catch (MalformedURLException ex) {
            //不是标准Url,则作为文件路径处理
            return new File(resourceLocation);
        }
    }

    // 利用URL获取File对象
    public static File getFile(URL resourceUrl) throws FileNotFoundException {
        return getFile(resourceUrl, "URL");
    }

    // 尝试利用URL获取File对象
    public static File getFile(URL resourceUrl, String description) throws FileNotFoundException {
        Assert.notNull(resourceUrl, "Resource URL must not be null");
        if (!URL_PROTOCOL_FILE.equals(resourceUrl.getProtocol())) {
            throw new FileNotFoundException(
                    description + " cannot be resolved to absolute file path " +
                    "because it does not reside in the file system: " + resourceUrl);
        }
        try {
            return new File(toURI(resourceUrl).getSchemeSpecificPart());
        }
        catch (URISyntaxException ex) {
            // Fallback for URLs that are not valid URIs (should hardly ever happen).
            return new File(resourceUrl.getFile());
        }
    }

    //通过给定URI获取文件对象
    public static File getFile(URI resourceUri) throws FileNotFoundException {
        return getFile(resourceUri, "URI");
    }


    //通过给定URI获取文件对象
    public static File getFile(URI resourceUri, String description) throws FileNotFoundException {
        Assert.notNull(resourceUri, "Resource URI must not be null");
        if (!URL_PROTOCOL_FILE.equals(resourceUri.getScheme())) {
            throw new FileNotFoundException(
                    description + " cannot be resolved to absolute file path " +
                    "because it does not reside in the file system: " + resourceUri);
        }
        return new File(resourceUri.getSchemeSpecificPart());
    }

    //判断给定的URL指向文件系统中。协议包含:"file", "vfsfile" or "vfs".
    public static boolean isFileURL(URL url) {
        String protocol = url.getProtocol();
        return (URL_PROTOCOL_FILE.equals(protocol) || URL_PROTOCOL_VFSFILE.equals(protocol) ||
                URL_PROTOCOL_VFS.equals(protocol));
    }


     //确定给定URL是否指向JAR文件中的资源。协议包含:"jar", "zip", "vfszip", "wsjar" or "code-source".
    public static boolean isJarURL(URL url) {
        String protocol = url.getProtocol();
        return (URL_PROTOCOL_JAR.equals(protocol) || URL_PROTOCOL_ZIP.equals(protocol) ||
                URL_PROTOCOL_VFSZIP.equals(protocol) || URL_PROTOCOL_WSJAR.equals(protocol) ||
                (URL_PROTOCOL_CODE_SOURCE.equals(protocol) && url.getPath().contains(JAR_URL_SEPARATOR)));
    }


     //从给定URL中提取实际JAR文件的URL(它可以指向JAR文件中的资源或JAR文件本身)
    public static URL extractJarFileURL(URL jarUrl) throws MalformedURLException {
        //获取路径:‘jar:http://hostname/my.jar!/’
        String urlFile = jarUrl.getFile();
        int separatorIndex = urlFile.indexOf(JAR_URL_SEPARATOR);
        if (separatorIndex != -1) {
            //截取后为:‘jar:http://hostname/my.jar’
            String jarFile = urlFile.substring(0, separatorIndex);
            try {
                return new URL(jarFile);
            }
            catch (MalformedURLException ex) {
                //可能在原始JAR URL中没有协议, 例如:‘jar:C:/mypath/myjar.jar’.
                //这通常表示JAR文件在文件系统中。
                if (!jarFile.startsWith("/")) {
                    //截取后:‘/mypath/myjar.jar’
                    jarFile = "/" + jarFile;
                }
                //标准URL加载:‘file:/mypath/myjar.jar’
                return new URL(FILE_URL_PREFIX + jarFile);
            }
        }
        else {
            return jarUrl;
        }
    }

    public static URI toURI(URL url) throws URISyntaxException {
        return toURI(url.toString());
    }

    public static URI toURI(String location) throws URISyntaxException {
        return new URI(StringUtils.replace(location, " ", "%20"));
    }

    /**
     * Set the {@link URLConnection#setUseCaches "useCaches"} flag on the
     * given connection, preferring {@code false} but leaving the
     * flag at {@code true} for JNLP based resources.
     * @param con the URLConnection to set the flag on
     */
    public static void useCachesIfNecessary(URLConnection con) {
        con.setUseCaches(con.getClass().getSimpleName().startsWith("JNLP"));
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值