如何读取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方法是普通的对象方法,你在普通的对象方法里,都是给实例变量赋值的,不是给静态变量赋值的,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实现单链表中是否有环的方法详解

    java实现单链表中是否有环的方法详解

    本篇文章介绍了,用java实现单链表中是否有环的方法详解。需要的朋友参考下
    2013-05-05
  • java单机接口限流处理方案详解

    java单机接口限流处理方案详解

    这篇文章主要为大家详细介绍了java单机接口限流处理方案,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-11-11
  • JUC循环屏障CyclicBarrier与CountDownLatch区别详解

    JUC循环屏障CyclicBarrier与CountDownLatch区别详解

    这篇文章主要为大家介绍了JUC循环屏障CyclicBarrier与CountDownLatch区别详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    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延迟队列执行流程源码解析

    Redisson延迟队列执行流程源码解析

    这篇文章主要为大家介绍了Redisson延迟队列执行流程源码解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-09-09

最新评论