最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

如何讀取properties或yml文件數(shù)據(jù)并匹配

 更新時(shí)間:2021年12月16日 16:34:17   作者:NoteDay  
這篇文章主要介紹了如何讀取properties或yml文件數(shù)據(jù)并匹配方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

讀取properties或yml文件數(shù)據(jù)并匹配

使用springboot獲取配置的文件的數(shù)據(jù)有多種方式,其中是通過注解@Value,此處通過IO獲取配置文件內(nèi)容。

此前已經(jīng)在另外的test.xml文件中的bean中可設(shè)置xx或yy,這里實(shí)現(xiàn)如果test.xml文件中沒有設(shè)置,可在application.*文件中進(jìn)行設(shè)置。

如下:

            try {
                InputStream stream = getClass().getClassLoader().getResourceAsStream("application.properties");
                if(stream == null){
                    stream = getClass().getClassLoader().getResourceAsStream("application.yml");
                    InputStreamReader in = new InputStreamReader(stream, "gbk");
                    BufferedReader reader = new BufferedReader(in);
                    String line;
                    while ((line = reader.readLine()) != null) {
                        if(line.trim().split(":")[0].contentEquals("xx")){
                       		 //在test.xml中讀取后可通過set傳值。這里也可以自己通過設(shè)置相應(yīng)參數(shù)的set方法進(jìn)行傳值
                            this.setXX(line.trim().split(":")[1].trim()); 
                        }else if(line.trim().split(":")[0].contentEquals("yy")){
                            this.setYY(line.trim().split(":")[1].trim());
                        }
                    }
                }else{
                    InputStreamReader in = new InputStreamReader(stream, "gbk");
                    BufferedReader reader = new BufferedReader(in);
                    String line;
                    while ((line = reader.readLine()) != null) {
                        if(line.trim().split("=")[0].contentEquals("xx")){
                        	//在test.xml中讀取后可通過set傳值。這里也可以自己通過設(shè)置相應(yīng)參數(shù)的set方法進(jìn)行傳值
                            this.setXX(line.trim().split(":")[1].trim()); 
                        }else if(line.trim().split("=")[0].contentEquals("yy")){
                            this.setYY(line.trim().split(":")[1].trim());
                        }
                    }
                }
            } catch (FileNotFoundException e) {
                logger.error("無法找到application.*文件",e);
            } catch (IOException e) {
                logger.error("讀取配置文件的ip或port有問題",e);
            }

讀取yml,properties配置文件幾種方式小結(jié)

1-@value

@Value("${keys}")
private String key;

這里需要注意的是

  • 當(dāng)前類要交給spring來管理
  • @Value不會(huì)賦值給static修飾的變量。

因?yàn)镾pring的@Value依賴注入是依賴set方法,而自動(dòng)生成的set方法是普通的對(duì)象方法,你在普通的對(duì)象方法里,都是給實(shí)例變量賦值的,不是給靜態(tài)變量賦值的,static修飾的變量,一般不生成set方法。若必須給static修飾的屬性賦值可以參考以下方法

private static String url;   
// 記得去掉static 
@Value("${mysql.url}") 
public void setDriver(String url) {      
    JdbcUtils.url= url; 
}

但是該方案有個(gè)弊端,數(shù)組應(yīng)該如何注入呢?

2-使用對(duì)象注入

auth: 
  clients: 
    - id:1
      password: 123
    - id: 2
      password: 123
@Component
@ConfigurationProperties(prefix="auth")
public class IgnoreImageIdConfig {
 private List<Map<String,String>> clients =new ArrayList<Integer>();
 
}

利用配置Javabean的形式來獲得值,值得注意的是,對(duì)象里面的引用名字(‘clients'),必須和yml文件中的(‘clients')一致,不然就會(huì)取不到數(shù)據(jù),另外一點(diǎn)是,數(shù)組這個(gè)對(duì)象必須先new出來,如果沒有對(duì)象的話也會(huì)取值失敗的,(同理map形式也必須先將map對(duì)應(yīng)的對(duì)象new出來)。

3-讀取配置文件

 private static final String FILE_PATH = "classpath:main_data_sync.yml";
    static Map<String, String> result = null;
    private static Properties properties = null;
    private YmlUtil() {
    }
    /**
     * 讀取yml的配置文件數(shù)據(jù)
     * @param filePath
     * @param keys
     * @return
     */
    public static Map<String, String> getYmlByFileName(String filePath, String... keys) {
        result = new HashMap<>(16);
        if (filePath == null) {
            filePath = FILE_PATH;
        }
        InputStream in = null;
        File file = null;
        try {
            file = ResourceUtils.getFile(filePath);
            in = new BufferedInputStream(new FileInputStream(file));
            Yaml props = new Yaml();
            Object obj = props.loadAs(in, Map.class);
            Map<String, Object> param = (Map<String, Object>) obj;
            for (Map.Entry<String, Object> entry : param.entrySet()) {
                String key = entry.getKey();
                Object val = entry.getValue();
                if (keys.length != 0 && !keys[0].equals(key)) {
                    continue;
                }
                if (val instanceof Map) {
                    forEachYaml(key, (Map<String, Object>) val, 1, keys);
                } else {
                    String value = val == null ? null : JSONObject.toJSONString(val);
                    result.put(key, value);
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return result;
    }
    public static Map<String, String> forEachYaml(String keyStr, Map<String, Object> obj, int i, String... keys) {
        for (Map.Entry<String, Object> entry : obj.entrySet()) {
            String key = entry.getKey();
            Object val = entry.getValue();
            if (keys.length > i && !keys[i].equals(key)) {
                continue;
            }
            String strNew = "";
            if (StringUtils.isNotEmpty(keyStr)) {
                strNew = keyStr + "." + key;
            } else {
                strNew = key;
            }
            if (val instanceof Map) {
                forEachYaml(strNew, (Map<String, Object>) val, ++i, keys);
                i--;
            } else {
                String value = val == null ? null : JSONObject.toJSONString(val);
                result.put(strNew, value);
            }
        }
        return result;
    }
    /**
     * 獲取Properties類型屬性值
     * @param filePath classpath:文件名
     * @param key key值
     * @return
     * @throws IOException
     */
    public static String getProperties(String filePath,String key) throws IOException {
        if (properties == null) {
            Properties prop = new Properties();
            //InputStream in = Util.class.getClassLoader().getResourceAsStream("testUrl.properties");
            InputStream in = new BufferedInputStream(new FileInputStream(ResourceUtils.getFile(filePath)))  ;
            prop.load(in);
            properties = prop;
        }
        return properties.getProperty(key);
    }
    public static void main(String[] args) {
        /*Map<String, String> cId = getYmlByFileName("classpath:test.yml", "auth", "clients");
        //cId.get("")
        String json = cId.get("auth.clients");
        List<Map> maps = JSONObject.parseArray(json, Map.class);
        System.out.println(maps);*/
        try {
            String properties = getProperties("classpath:test.properties", "fileServerOperator.beanName");
            System.out.println(properties);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
auth:  #認(rèn)證
  clients:
    - id: 1
      secretKey: ba2631ee44149bbe #密鑰key
    - id: 2
      secretKey: ba2631ee44149bbe #密鑰key

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Java實(shí)現(xiàn)讀取Excel文件功能(EasyExcel初使用)

    Java實(shí)現(xiàn)讀取Excel文件功能(EasyExcel初使用)

    EasyExcel是一款基于Java語言的開源Excel解析工具,可以幫助我們快速、高效地讀取和寫入Excel文件,這篇文章主要給大家介紹了關(guān)于Java實(shí)現(xiàn)讀取Excel文件功能的相關(guān)資料,使用的是EasyExcel,需要的朋友可以參考下
    2024-07-07
  • idea 模板編程知識(shí)小結(jié)

    idea 模板編程知識(shí)小結(jié)

    這篇文章主要介紹了idea 模板編程的相關(guān)知識(shí),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-08-08
  • Hibernate Validation自定義注解校驗(yàn)的實(shí)現(xiàn)

    Hibernate Validation自定義注解校驗(yàn)的實(shí)現(xiàn)

    這篇文章主要介紹了Hibernate Validation自定義注解校驗(yàn)的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-04-04
  • SpringBoot使用Redis Stream實(shí)現(xiàn)輕量消息隊(duì)列的示例代碼

    SpringBoot使用Redis Stream實(shí)現(xiàn)輕量消息隊(duì)列的示例代碼

    Redis Stream 是 Redis 5.0 引入的一種數(shù)據(jù)結(jié)構(gòu),用于處理日志類型的數(shù)據(jù),它提供了高效、可靠的方式來處理和存儲(chǔ)時(shí)間序列數(shù)據(jù),如事件、消息等,本文介紹了SpringBoot使用Redis Stream實(shí)現(xiàn)輕量消息隊(duì)列,需要的朋友可以參考下
    2024-08-08
  • 一起來學(xué)習(xí)Java的棧和隊(duì)列

    一起來學(xué)習(xí)Java的棧和隊(duì)列

    這篇文章主要為大家詳細(xì)介紹了Java的棧和隊(duì)列,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
    2022-03-03
  • Spring Boot 各種回滾操作實(shí)戰(zhàn)教程(自動(dòng)回滾、手動(dòng)回滾、部分回滾)

    Spring Boot 各種回滾操作實(shí)戰(zhàn)教程(自動(dòng)回滾、手動(dòng)回滾、部分回滾)

    這篇文章主要介紹了Spring Boot 各種回滾操作實(shí)戰(zhàn)教程(自動(dòng)回滾、手動(dòng)回滾、部分回滾),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-07-07
  • Java事件機(jī)制要素及實(shí)例詳解

    Java事件機(jī)制要素及實(shí)例詳解

    這篇文章主要介紹了Java事件機(jī)制要素及實(shí)例詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-04-04
  • java開發(fā)hutool HttpUtil網(wǎng)絡(luò)請(qǐng)求工具使用demo

    java開發(fā)hutool HttpUtil網(wǎng)絡(luò)請(qǐng)求工具使用demo

    這篇文章主要為大家介紹了hutool之HttpUtil網(wǎng)絡(luò)請(qǐng)求工具使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-07-07
  • java向es中寫入數(shù)據(jù)報(bào)錯(cuò)org.elasticsearch.action.ActionReque問題

    java向es中寫入數(shù)據(jù)報(bào)錯(cuò)org.elasticsearch.action.ActionReque問題

    這篇文章主要介紹了java向es中寫入數(shù)據(jù)報(bào)錯(cuò)org.elasticsearch.action.ActionReque問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-11-11
  • Java日常練習(xí)題,每天進(jìn)步一點(diǎn)點(diǎn)(57)

    Java日常練習(xí)題,每天進(jìn)步一點(diǎn)點(diǎn)(57)

    下面小編就為大家?guī)硪黄狫ava基礎(chǔ)的幾道練習(xí)題(分享)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧,希望可以幫到你
    2021-08-08

最新評(píng)論

琼海市| 陆川县| 巴彦县| 华池县| 冕宁县| 山西省| 盘山县| 建宁县| 新邵县| 山阳县| 昭苏县| 桃园市| 宁陕县| 海口市| 浠水县| 无锡市| 新疆| 资溪县| 昌乐县| 乡宁县| 行唐县| 青海省| 宁城县| 霍城县| 广宁县| 贵南县| 金溪县| 怀柔区| 邮箱| 赤水市| 秭归县| 青冈县| 菏泽市| 射阳县| 洛扎县| 常宁市| 商南县| 玉林市| 涿鹿县| 荔波县| 德昌县|