SpringBoot源碼學習系列之@PropertySource不支持yaml讀取原因


然后,為什么@PropertySource注解默認不支持?可以簡單跟一下源碼

@PropertySource源碼:
在這里插入圖片描述
根據注釋,默認使用DefaultPropertySourceFactory類作為資源文件加載類
在這里插入圖片描述
里面還是調用Spring框架底層的PropertiesLoaderUtils工具類進行讀取的
在這里插入圖片描述
PropertiesLoaderUtils.loadProperties
在這里插入圖片描述
從源碼可以看出也是支持xml文件讀取的,能支持reader就獲取reader對象,否則出件inputStream
在這里插入圖片描述

在這里插入圖片描述
load0方法是關鍵,這里加了同步鎖
在這里插入圖片描述
很重要的load0 方法抓取出來:

private void load0 (LineReader lr) throws IOException {
        char[] convtBuf = new char[1024];
        int limit;
        // 當前key所在位置
        int keyLen;
        // 當前value所在位置
        int valueStart;
        char c;//讀取的字符
        boolean hasSep;
        boolean precedingBackslash;//是否轉義字符,eg:/n etc.
		// 一行一行地讀取
        while ((limit = lr.readLine()) >= 0) {
            c = 0;
            keyLen = 0;
            valueStart = limit;
            hasSep = false;

            //System.out.println("line=<" + new String(lineBuf, 0, limit) + ">");
            precedingBackslash = false;
            //key的長度小於總的字符長度,那么就進入循環
            while (keyLen < limit) {
                c = lr.lineBuf[keyLen];
                //need check if escaped.
                if ((c == '=' ||  c == ':') && !precedingBackslash) {
                    valueStart = keyLen + 1;
                    hasSep = true;
                    break;
                } else if ((c == ' ' || c == '\t' ||  c == '\f') && !precedingBackslash) {
                    valueStart = keyLen + 1;
                    break;
                }
                if (c == '\\') {
                    precedingBackslash = !precedingBackslash;
                } else {
                    precedingBackslash = false;
                }
                keyLen++;
            }
            //value的起始位置小於總的字符長度,那么就進入該循環
            while (valueStart < limit) {
                c = lr.lineBuf[valueStart];
                //當前字符是否非空格類字符
                if (c != ' ' && c != '\t' &&  c != '\f') {
                    if (!hasSep && (c == '=' ||  c == ':')) {
                        hasSep = true;
                    } else {
                        break;
                    }
                }
                valueStart++;
            }
            //讀取key
            String key = loadConvert(lr.lineBuf, 0, keyLen, convtBuf);
            //讀取value
            String value = loadConvert(lr.lineBuf, valueStart, limit - valueStart, convtBuf);
            put(key, value);
        }
    }

ok,從源碼可以看出,這個方法是一行一行地讀取,然后根據冒號、等於號、空格等進行校驗,經過一系列遍歷之后獲取key和value,而yaml語法是以縮進來辨別的,經過自己調試,這個方法也是不支持yaml文件的讀取的,properties源碼是比較多的,具體的Properties源碼實現的可以參考博客:https://www.cnblogs.com/liuming1992/p/4360310.html,這篇博客寫的比較詳細

然后要支持的話,具體怎么實現,參考我博客:SpringBoot系列之@PropertySource讀取yaml文件


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM