如何读取properties或yml文件数据并匹配

目录
  • 读取properties或yml文件数据并匹配
  • 读取yml,properties配置文件几种方式小结
    • 1-@value
    • 2-使用对象注入
    • 3-读取配置文件

读取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

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • @Value如何获取yml和properties配置参数

    @Value获取yml和properties配置参数 Yml: #定时任务配置 application: xxl: job: enabled: true admin: addresses: http:///yusp-job-admin/ #127.0.0.1:8080指网关ip:port,yusp-job-admin为调度中心服务名称.通过网关,注册到微服务的/api/server接口,完成注册动作 executor: appname: af_job #执行器名称,要求务必唯一 ip: 10.2

  • SpringBoot读取properties或者application.yml配置文件中的数据

    读取application文件 在application.yml或者properties文件中添加: user.address=china user.company=demo user.name=让我康康 1.使用@Value注解读取 直接 代码如下: package im.homeapi.controller; import org.springframework.beans.factory.annotation.Value; import org.omg.CORBA.PUBLIC_MEMBE

  • SpringBoot获取yml和properties配置文件的内容

    (一)yml配置文件: pom.xml加入依赖: <!-- 支持 @ConfigurationProperties 注解 --> <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-configuration-processor --> <dependency> <groupId>org.springframework.boot</groupId>

  • 如何读取properties或yml文件数据并匹配

    目录 读取properties或yml文件数据并匹配 读取yml,properties配置文件几种方式小结 1-@value 2-使用对象注入 3-读取配置文件 读取properties或yml文件数据并匹配 使用springboot获取配置的文件的数据有多种方式,其中是通过注解@Value,此处通过IO获取配置文件内容. 此前已经在另外的test.xml文件中的bean中可设置xx或yy,这里实现如果test.xml文件中没有设置,可在application.*文件中进行设置. 如下: try

  • PHP读取并输出XML文件数据的简单实现方法

    本文实例讲述了PHP读取并输出XML文件数据的简单实现方法.分享给大家供大家参考,具体如下: config.XML文件: <?xml version="1.0" encoding="UTF-8"?> <node> <student> <name>张明</name> <email>1234567890@qq.com</email> <username>一样菜</use

  • JavaScript实现读取与输出XML文件数据的方法示例

    本文实例讲述了JavaScript实现读取与输出XML文件数据的方法.分享给大家供大家参考,具体如下: 一.介绍 通过JavaScript读取XML文档中数据的方法很多. 其根本的思路就是:首先在后台加载XML文档,然后通过JavaScript获取文档中所需的数据,最后应用HTML展示获取的数据. 二.获取XML元素的属性值的应用 下面应用attributes属性和getNamedItem()方法获取一个指定的XML文档中的属性值. 三.代码 首先创建一个XML文档,并且为指定的元素设置属性,程

  • python读取查看npz/npy文件数据以及数据完全显示方法实例

    目录 python读取npz/npy文件 python查看npz/npy文件 附:python-读取和保存npy文件示例代码 总结 python读取npz/npy文件 npz和npy文件都可以直接使用numpy读写. import numpy as np ac = np.load('mydata.npz') ac.files python查看npz/npy文件 要查看其中某一项的数据: M = ac['M'] M 显示的值带省略号,要完全显示,执行: np.set_printoptions(th

  • SpringBoot中5种高大上的yml文件读取方式

    目录 1.Environment 2.YamlPropertiesFactoryBean 3.监听事件 4.SnakeYml 5.jackson-dataformat-yaml 总结 在上一篇文章中,我们从源码角度分析了SpringBoot解析yml配置文件的全流程,那么我们今天就来点实战,总结一下除了烂大街的@Value和@ConfigurationProperties外,还能够通过哪些方式,来读取yml配置文件的内容. 1.Environment 在Spring中有一个类Environmen

  • spring-boot读取props和yml配置文件的方法

    最近微框架spring-boot很火,笔者也跟风学习了一下,废话不多说,现给出一个读取配置文件的例子. 首先,需要在pom文件中依赖以下jar包 <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <d

  • 基于springBoot配置文件properties和yml中数组的写法

    目录 springBoot配置文件properties和yml数组写法 这两种方法你选择哪种都可以 .properties和.yml的写法区别 springBoot配置文件properties和yml数组写法 这里介绍一下springBoot中的两种文件配置方式中数组的使用,也就是集合. 以下是我springBoot中使用的 application.properties 文件 其实很好理解,我的configs是一个集合,configs[0].appid代表我配置的第一个对象中的appid的值 m

  • ajax读取properties资源文件数据的方法

    本文实例讲述了ajax读取properties资源文件数据的方法.分享给大家供大家参考.具体实现方法如下: properties资源文件的内容如下: hello=englishww name=english zk emailEmpty=Field cannot be empty! emailInvalid=Invalid email address! js调用ajax处理代码: $.ajax({ type:'POST', dataType:'json', url:'/jeecms/jeecms/

  • spring无法读取properties文件数据问题详解

    1. controller中无法读取config.properties文件 controller中注入的@Value配置是从servlet-context.xml配置文件中获取的:service中注入的@Value配置可以从applicationContext.xml中获取的.所以,如果要在controller中注入属性配置,需要在相应servlet文件中添加配置,同applicationContext.xml中一样. <bean class="org.springframework.be

随机推荐