欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

如何讀取properties或yml文件數據并匹配

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

讀取properties或yml文件數據并匹配

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

此前已經在另外的test.xml文件中的bean中可設置xx或yy,這里實現如果test.xml文件中沒有設置,可在application.*文件中進行設置。

如下:

            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傳值。這里也可以自己通過設置相應參數的set方法進行傳值
                            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傳值。這里也可以自己通過設置相應參數的set方法進行傳值
                            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配置文件幾種方式小結

1-@value

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

這里需要注意的是

  • 當前類要交給spring來管理
  • @Value不會賦值給static修飾的變量。

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

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

但是該方案有個弊端,數組應該如何注入呢?

2-使用對象注入

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的形式來獲得值,值得注意的是,對象里面的引用名字(‘clients'),必須和yml文件中的(‘clients')一致,不然就會取不到數據,另外一點是,數組這個對象必須先new出來,如果沒有對象的話也會取值失敗的,(同理map形式也必須先將map對應的對象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的配置文件數據
     * @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:  #認證
  clients:
    - id: 1
      secretKey: ba2631ee44149bbe #密鑰key
    - id: 2
      secretKey: ba2631ee44149bbe #密鑰key

以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關文章

  • springboot+zookeeper實現分布式鎖的示例代碼

    springboot+zookeeper實現分布式鎖的示例代碼

    本文主要介紹了springboot+zookeeper實現分布式鎖的示例代碼,文中根據實例編碼詳細介紹的十分詳盡,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-03-03
  • SpringData整合ElasticSearch實現CRUD的示例代碼(超詳細)

    SpringData整合ElasticSearch實現CRUD的示例代碼(超詳細)

    本文主要介紹了SpringData整合ElasticSearch實現CRUD的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2023-07-07
  • 前端如何傳遞Array、Map類型數據到Java后端

    前端如何傳遞Array、Map類型數據到Java后端

    這篇文章主要給大家介紹了關于前端如何傳遞Array、Map類型數據到Java后端的相關資料,文中通過圖文介紹的非常詳細,對大家的學習或者工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2024-01-01
  • java實現單鏈表中是否有環(huán)的方法詳解

    java實現單鏈表中是否有環(huán)的方法詳解

    本篇文章介紹了,用java實現單鏈表中是否有環(huán)的方法詳解。需要的朋友參考下
    2013-05-05
  • java單機接口限流處理方案詳解

    java單機接口限流處理方案詳解

    這篇文章主要為大家詳細介紹了java單機接口限流處理方案,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-11-11
  • JUC循環(huán)屏障CyclicBarrier與CountDownLatch區(qū)別詳解

    JUC循環(huán)屏障CyclicBarrier與CountDownLatch區(qū)別詳解

    這篇文章主要為大家介紹了JUC循環(huán)屏障CyclicBarrier與CountDownLatch區(qū)別詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-12-12
  • @Async異步線程池以及線程的命名方式

    @Async異步線程池以及線程的命名方式

    這篇文章主要介紹了@Async異步線程池以及線程的命名方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-06-06
  • Springboot2.0配置JPA多數據源連接兩個mysql數據庫方式

    Springboot2.0配置JPA多數據源連接兩個mysql數據庫方式

    這篇文章主要介紹了Springboot2.0配置JPA多數據源連接兩個mysql數據庫方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • 深入學習Spring Cloud-Ribbon

    深入學習Spring Cloud-Ribbon

    這篇文章主要介紹了Spring Cloud-Ribbon的相關知識,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友一起看看吧
    2021-03-03
  • Redisson延遲隊列執(zhí)行流程源碼解析

    Redisson延遲隊列執(zhí)行流程源碼解析

    這篇文章主要為大家介紹了Redisson延遲隊列執(zhí)行流程源碼解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-09-09

最新評論