天天看點

Spring源碼之Resource加載源碼解析(一)

Spring中資源處理架構

Spring源碼之Resource加載源碼解析(一)

接口解析:

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"));
    }

}           

繼續閱讀