properties文件怎么读取里面数据(properties文件数据怎么获取)

技术怎样读取properties或yml文件数据并匹配今天就跟大家聊聊有关怎样读取properties或yml文件数据并匹配,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有

今天,我将与您讨论如何读取属性或yml文件数据并进行匹配。可能很多人不太了解。为了让大家更好的了解,边肖为大家总结了以下内容。希望你能从这篇文章中有所收获。

00-1010使用springboot获取配置文件的数据的方式有很多,其中使用了@Value的标注,这里配置文件的内容是通过IO获取的。

以前,xx或yy可以在另一个test.xml文件的bean中设置。如果没有在test.xml文件中设置,可以在应用程序中设置。*文件。

如下所示:

尝试{

InputStreamstream=getClass()。getClassLoader()。getResourceAsStream(' application . properties ');

if(stream==null){ 0

stream=getClass()。getClassLoader()。getResourceAsStream(' application . yml ');

InputStreamReaderin=new inputstreamreader(stream,‘gbk’);

bufferedreader=new bufferedreader(in);

Stringline

while((line=reader.readLine())!=null){ 0

if(line.trim()。拆分(' :')[0]。content equals(' xx '){ 0

//读入test.xml后,可以通过set传递值。在这里,您也可以通过自己设置相应参数的设置方法来传递该值。

this.setXX(line.trim()。拆分(' :')[1]。trim());

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

看完上述内容,你们对怎样读取properties或yml文件数据并匹配有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注行业资讯频道,感谢大家的支持。

内容来源网络,如有侵权,联系删除,本文地址:https://www.230890.com/zhan/151109.html

(0)

相关推荐

  • Centos8 下部署 ASP.net Core 程序

    技术Centos8 下部署 ASP.net Core 程序 Centos8 下部署 ASP.net Core 程序1、安装需要的SDK包,如果程序包含3.1版本,需要安装3.1的SDK。
    sudo dn

    礼包 2021年12月1日
  • Elasticsearch有哪些面试题

    技术Elasticsearch有哪些面试题这篇文章主要为大家展示了“Elasticsearch有哪些面试题”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“Elasticsear

    攻略 2021年11月17日
  • Python操作Word文档docx的常用方法有哪些

    技术Python操作Word文档docx的常用方法有哪些这篇文章主要介绍Python操作Word文档docx的常用方法有哪些,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!安装docx是一个非标准库

    攻略 2021年10月30日
  • 污的句子,很乖很奇怪很污很可爱之类的句子

    技术污的句子,很乖很奇怪很污很可爱之类的句子1、他大约有十三、四岁。又黑又胖的小脸上污的句子,嵌着一个尖尖的翘鼻子。长长的头发,好久没理了。浓浓的眉毛下闪着一对大眼睛,乌黑的眼珠挺神气地转来转去。 2、树丛被拨开了,一个

    生活 2021年10月29日
  • 盐酸和碳酸钠反应的化学方程式,碳酸氢钠和盐酸反应的化学方程式

    技术盐酸和碳酸钠反应的化学方程式,碳酸氢钠和盐酸反应的化学方程式碳酸氢钠和盐酸的反应化学方程式盐酸和碳酸钠反应的化学方程式:NaHCO3+HCl=NaCl+CO2↑+H2O碳酸氢钠和盐酸的反应离子方程式:
    HCO3- +

    生活 2021年10月29日
  • 正气宝的功效与作用,麻黄的功效是什么,有什么禁忌

    技术正气宝的功效与作用,麻黄的功效是什么,有什么禁忌麻黄为麻黄科植物草麻黄正气宝的功效与作用、中麻黄或木贼麻黄的干燥草质茎,属于发散风寒药。麻黄主要含麻黄碱、伪麻黄碱、去甲基麻黄碱、去甲基伪麻黄碱、甲基麻黄碱、甲基伪麻黄

    生活 2021年10月27日