spring resource以及ant路徑匹配規則 源碼學習

spring中resource是一個接口,為資源的抽象提供了一套操作方式,可匹配類似于classpath:XXX,file://XXX等不同協議的資源訪問。

image.png

如上圖所示,spring已經提供了多種訪問資源的實體類,還有DefaultResourceLoader類,使得與具體的context結合。在spring中根據設置的配置文件路徑轉換為對應的文件資源


// AbstractBeanDefinitionReader 文件
Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);

// 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;
        }
    }

    if (location.startsWith("/")) {
       // ClassPathContextResource 
        return getResourceByPath(location);
    }
    else if (location.startsWith(CLASSPATH_URL_PREFIX)) {
        return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
        // 如果是以classpath:開頭,認為是classpath樣式的資源,返回ClassPathResource
    }
    else {
        try {
            URL url = new URL(location);
            return new UrlResource(url);
            // 符合URL協議,返回UrlResource
        }
        catch (MalformedURLException ex) {
            return getResourceByPath(location);
            // 剩下的無法判斷的全部返回ClassPathContextResource
        }
    }
}

// 然后在真正的使用resource的文件流時,XmlBeanDefinitionReader文件內
InputStream inputStream = encodedResource.getResource().getInputStream();
image.png

有多種具體的Resource類的獲取輸入流的實現方式。
FileSystemResource 類

    public InputStream getInputStream() throws IOException {
        return new FileInputStream(this.file);
        // this.file 是個File對象
    }

ClassPathContextResource和ClassPathResource的獲取IO流的方法是同一個

現在基本上清楚了spring針對不同協議的文件路徑是如何操作路徑,以什么樣子的方式獲取IO流,不過還是有幾個疑問需要深入了解下。

  • 如何匹配多個資源文件
  • FileSystemXmlApplicationContext和ClassPathXmlApplicationContext的區別

匹配多個資源文件

之前說的例子都是明確指定context.xml 的情況,可是現實中會配置多個配置文件,然后依次加載,例如*.xml會匹配當前目錄下面所有的.xml文件。來到了PathMatchingResourcePatternResolver.class匹配出多個xml的情況

至于為什么會定位到PathMatchingResourcePatternResolver.class這個文件,可以看

AbstractApplicationContext 文件

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

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

// 也就意味著在context類初始化的時候,就直接設置了好了resourcePatternResolver對象為PathMatchingResourcePatternResolver

PathMatchingResourcePatternResolver 文件

public Resource[] getResources(String locationPattern) throws IOException {
    Assert.notNull(locationPattern, "Location pattern must not be null");
    if (locationPattern.startsWith(CLASSPATH_ALL_URL_PREFIX)) {
        // 通過classpath:開頭的地址
        if (getPathMatcher().isPattern(locationPattern.substring(CLASSPATH_ALL_URL_PREFIX.length()))) {
            // 地址路徑中包含了 【*】這個匹配的關鍵字,意味著要模糊匹配
            return findPathMatchingResources(locationPattern);
        }
        else {
            // 查找當前所有的classpath資源并返回
            return findAllClassPathResources(locationPattern.substring(CLASSPATH_ALL_URL_PREFIX.length()));
        }
    }
    else {
        // and on Tomcat only after the "*/" separator for its "war:" protocol.
        int prefixEnd = (locationPattern.startsWith("war:") ? locationPattern.indexOf("*/") + 1 :
                locationPattern.indexOf(":") + 1);
        if (getPathMatcher().isPattern(locationPattern.substring(prefixEnd))) {
            // 除去前綴,包含【*】,進行模糊匹配
            return findPathMatchingResources(locationPattern);
        }
        else {
            // 這個是針對具體的xml文件的匹配規則,會進入到DefaultResourceLoader裝載資源文件
            return new Resource[] {getResourceLoader().getResource(locationPattern)};
        }
    }
}


// 根據模糊地址找出所有匹配的資源文件
protected Resource[] findPathMatchingResources(String locationPattern) throws IOException {
    String rootDirPath = determineRootDir(locationPattern);
    // 根路徑,此處為xml/
    String subPattern = locationPattern.substring(rootDirPath.length());
    // 子路徑,此處為*.xml
    Resource[] rootDirResources = getResources(rootDirPath);
    // 調用本身,算出根路徑的資源信息
    // 如果為xml/*.xml 則返回一個根路徑資源信息xml/
    // 如果為xml/**/*.xml 則還是返回一組根路徑資源信息xml/
    Set<Resource> result = new LinkedHashSet<Resource>(16);
    for (Resource rootDirResource : rootDirResources) {
        rootDirResource = resolveRootDirResource(rootDirResource);
        URL rootDirURL = rootDirResource.getURL();
        // 獲取其URL信息
        if (equinoxResolveMethod != null) {
            if (rootDirURL.getProtocol().startsWith("bundle")) {
                rootDirURL = (URL) ReflectionUtils.invokeMethod(equinoxResolveMethod, null, rootDirURL);
                rootDirResource = new UrlResource(rootDirURL);
            }
        }
        if (rootDirURL.getProtocol().startsWith(ResourceUtils.URL_PROTOCOL_VFS)) {
        // jboss的文件協議
            result.addAll(VfsResourceMatchingDelegate.findMatchingResources(rootDirURL, subPattern, getPathMatcher()));
        }
        else if (ResourceUtils.isJarURL(rootDirURL) || 
        isJarResource(rootDirResource)) {
           // jar包
            result.addAll(doFindPathMatchingJarResources(rootDirResource, rootDirURL, subPattern));
        }
        else {
           // 默認掃描當前的所有資源,添加到result中
            result.addAll(doFindPathMatchingFileResources(rootDirResource, subPattern));
        }
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Resolved location pattern [" + locationPattern + "] to resources " + result);
    }
    return result.toArray(new Resource[result.size()]);
}

// 通過路徑去匹配到合適的資源,此處的rootDir包含了絕對路徑
protected Set<File> retrieveMatchingFiles(File rootDir, String pattern) 
      throws IOException {
    if (!rootDir.exists()) {
       // 根路徑都不存在,則返回空
        if (logger.isDebugEnabled()) {
            logger.debug("Skipping [" + rootDir.getAbsolutePath() + "] because it does not exist");
        }
        return Collections.emptySet();
    }
    if (!rootDir.isDirectory()) {
        // 不是文件夾,返回空
        if (logger.isWarnEnabled()) {
            logger.warn("Skipping [" + rootDir.getAbsolutePath() + "] because it does not denote a directory");
        }
        return Collections.emptySet();
    }
    if (!rootDir.canRead()) {
       // 文件不可讀,也返回空
        if (logger.isWarnEnabled()) {
            logger.warn("Cannot search for matching files underneath directory [" + rootDir.getAbsolutePath() +
                    "] because the application is not allowed to read the directory");
        }
        return Collections.emptySet();
    }
    String fullPattern = StringUtils.replace(rootDir.getAbsolutePath(), File.separator, "/");
    // 得到當前系統下的文件絕對地址
    if (!pattern.startsWith("/")) {
        fullPattern += "/";
    }
    fullPattern = fullPattern + StringUtils.replace(pattern, File.separator, "/");
    // 得到完整的全路徑 例如/user/...*.xml
    Set<File> result = new LinkedHashSet<File>(8);
    doRetrieveMatchingFiles(fullPattern, rootDir, result);
    // 得到當前rootDir下面的所有文件,然后配合fullPattern進行匹配,得到的結果在result中
    return result;
}

protected void doRetrieveMatchingFiles(String fullPattern, File dir, Set<File> result) throws IOException {
    if (logger.isDebugEnabled()) {
        logger.debug("Searching directory [" + dir.getAbsolutePath() +
                "] for files matching pattern [" + fullPattern + "]");
    }
    File[] dirContents = dir.listFiles();
    // 得到當前根路徑的所有文件(包含了文件夾)
    if (dirContents == null) {
        if (logger.isWarnEnabled()) {
            logger.warn("Could not retrieve contents of directory [" + dir.getAbsolutePath() + "]");
        }
        return;
    }
    Arrays.sort(dirContents);
    // 這個也需要注意到,這個順序決定了掃描文件的先后順序,也意味著bean加載的情況
    for (File content : dirContents) {
        String currPath = StringUtils.replace(content.getAbsolutePath(), File.separator, "/");
        if (content.isDirectory() && getPathMatcher().matchStart(fullPattern, currPath + "/")) {
          // 如果是文件夾,類似于xml/**/*.xml 文件
          // 訪問到了** 就會是文件夾
            if (!content.canRead()) {
                ...
            }
            else {
               // 循環迭代訪問文件
                doRetrieveMatchingFiles(fullPattern, content, result);
            }
        }
        if (getPathMatcher().match(fullPattern, currPath)) {
            result.add(content);
            // 匹配完成,添加到結果集合中
        }
    }
}

這樣整個的xml文件讀取過程就全部完成,也清楚了實際中xml文件是什么樣的形式被訪問到的。
其實spring的路徑風格是和Apache Ant的路徑樣式一樣的,Ant的更多細節可以自行學習了解。

FileSystemXmlApplicationContext和ClassPathXmlApplicationContext的區別

這個看名字就很明顯,就是加載文件不太一樣,一個通過純粹的文件協議去訪問,另一個卻可以兼容多種協議。仔細分析他們的差異,會發現主要的差異就在于FileSystemXmlApplicationContext重寫的getResourceByPath方法

FileSystemXmlApplicationContext 文件

protected Resource getResourceByPath(String path) {
    if (path != null && path.startsWith("/")) {
        path = path.substring(1);
    }
    return new FileSystemResource(path);
}

上面代碼學習,已經清楚了在默認的中是生成ClassPathContextResource資源,但是重寫之后意味著被強制性的設置為了FileSystemResource,就會出現文件不存在的情況。

如下圖,設置的path只有context.xml,就會被提示找不到文件,因為此時的文件路徑是項目路徑 + context.xml

image.png

如果改為使用simple-spring-demo/src/main/resources/context.xml,此時需要注意修改xml內的properties文件路徑,否則也會提示文件找不到

image.png

image.png

這樣就符合設置了,運行正常,這也告訴我們一旦使用FileSystemXmlApplicationContext記得修改所有的路徑配置,以防止出現文件找不到的錯誤。

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,362評論 6 544
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,577評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,486評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,852評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,600評論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,944評論 1 328
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,944評論 3 447
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 43,108評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,652評論 1 336
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,385評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,616評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,111評論 5 364
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,798評論 3 350
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,205評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,537評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,334評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,570評論 2 379

推薦閱讀更多精彩內容

  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,828評論 18 139
  • Spring Boot 參考指南 介紹 轉載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,922評論 6 342
  • 尋春?得到鄉下——城里沒有分明的四季,就如沒有真正的夜晚。 跟我回鄉吧。 春早來了呢,在鄉下。 春天在小河邊。 小...
    木棉之秋閱讀 940評論 79 48
  • 明天公司又要開盤了,最近的售樓部真的是門庭若市,和我們本身的高端調性還有點不搭。誰叫今年市場好呢?誰叫國人買漲不買...
    杜美慧閱讀 412評論 0 0
  • “死亡”是令我們恐懼的一個詞,很多時候,我們都會避諱提及這兩個字。 事實上,伴隨死亡而來的一切比死亡本身更可怕。 ...
    WendyKoo閱讀 386評論 3 3