springboot之json/yml配置文件的读取

Untitled

配置文件读取

项目根目录的config目录下person.yml, 文件夹如下

person:
  name: qinjiang
  age: 3
  happy: false
  birth: 2000/01/01
  maps: {k1: v1, k2: v2}
  lists:
    - code
    - girl
    - music
  dog:
    name: 旺财
    age: 1

device.json文件

{
  "id": 23,
  "name": "robot",
  "state": 2,
  "point": [
    1,
    2
  ]
}

单个注入: @Value

可用于json/yml文件

@Component
@PropertySource(value = {"file:./config/person.yml"},factory = YamlPropertySourceFactory.class)
@PropertySource(value = {"file:./config/device.json"})
public class Cat {
    @Value("${person.dog.name}")
    @value(${id})  // device.json文件中的字段
    private String name;

    @Bean
    public void testValue(){
        System.out.println("field name is injected through @Value:" + name);
    }
}
________________________________________

field name is injected through @Value:旺财

批量注入: @ConfigurationProperties注解

yml文件

这个注解常用于yml文件, 可以通过@PropertySource注解指定配置文件的路径. 其中file:./config/person.yml表示的项目的根路径下的文件夹config下文件person,.yml, 可以发现它是按名字匹配的.

package com.wang.yml;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Person : TODO
 *
 * @author : Wangwenchu
 * @since : 2023/1/12
 */
@Data
@Component
@ConfigurationProperties(prefix = "person")
@PropertySource(value = {"file:./config/person.yml"},factory = YamlPropertySourceFactory.class)
public class Person {
    private String name;
    private Integer age;
    private Boolean happy;
    private Date birth;
    private Map<String,Object> maps;
    private List<Object> lists;
 
    private Dog dog;
}

@Data
public class Dog {
    private String name;
    private int age;
}

-------------------------------------
Person(name=qinjiang, age=3, happy=false, birth=Sat Jan 01 00:00:00 CST 2000, 
maps={k1=v1, k2=v2}, lists=[code, girl, music], dog=Dog(name=旺财, age=1))

其中YamlPropertySourceFactory为:

package com.wang.yml;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

/**
/ * YamlPropertySourceFactory : TODO
 *
 * @author : Wangwenchu
 * @since : 2023/1/13
 */
public class YamlPropertySourceFactory implements PropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String sourceName, EncodedResource resource) throws IOException {
        Properties propertiesFromYaml = loadYaml(resource);
        if(sourceName == null || sourceName.length() == 0){
            sourceName =  resource.getResource().getFilename();;
        }

        return new PropertiesPropertySource(sourceName, propertiesFromYaml);
    }
    private Properties loadYaml(EncodedResource resource) throws FileNotFoundException {
        try {
            YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
            factory.setResources(resource.getResource());
            factory.afterPropertiesSet();
            return factory.getObject();
        } catch (IllegalStateException e) {
            // for ignoreResourceNotFound
            Throwable cause = e.getCause();
            if (cause instanceof FileNotFoundException)
                throw (FileNotFoundException) e.getCause();
            throw e;
        }
    }
}

补充

  • file: ./config 工程根目录下config目录
  • classpath:/config/ jar包内的文件目录, 对应于resource目录

json文件读取

导入fastjson的maven依赖:

<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
</dependency>

常用的操作

获取单个属性

以下面的device.json为例:

{
  "id": 23,
  "name": "robot",
  "state": 2,
  "point": [
    1,
    2
  ]
}
  • json path -- > File --> String --> JSONObject --> 调用getString(name)
  public void getPropertyFromObject() {
        String path = System.getProperty("user.dir") + File.separator + "config" + File.separator + "device.json";
        File file = new File(path);
        try {
            String json = FileUtils.readFileToString(file);
            JSONObject jsonObject = JSONObject.parseObject(json);
            System.out.println("name:" + jsonObject.getString("name"));

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
   }
_________________________
name:robot

JSON.parseObject实现转为, 注意也是按照属性名和配置文件中的相匹配(大小写忽略), 没有的字段为null, 存在的就注入

 public void getObject() {
        String path = System.getProperty("user.dir") + File.separator + "config" + File.separator + "device.json";
        File file = new File(path);
        try {
            String json = FileUtils.readFileToString(file);
            Robot config = JSON.parseObject(json,Robot.class);
            System.out.println(config.getId());  
            System.out.println(config.getName());
            System.out.println(config.getState());
            System.out.println(config.getCode());  // null
            System.out.println(config.getPoint().get(0));

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

___________________
23
robot
2
null
1

object-->jsonString

 public static void obj2JsonStr() {
        Robot robot = new Robot();
        robot.setId("001");
        robot.setName("v7");
        robot.setPoint(Arrays.asList(new String[]{"a", "b"}));
        robot.setCode("err");
        robot.setState(0);
        String jsonStr = JSON.toJSONString(robot);
        System.out.println(jsonStr); 
    }
-----------------------------
{"code":"err","id":"001","name":"v7","point":["a","b"],"state":0}

list(object)-->jsonString

 public static void listObj2JsonStr() {
        Robot robot1 = new Robot();
        robot1.setId("001");
        robot1.setName("v7");
        robot1.setPoint(Arrays.asList(new String[]{"a", "b"}));
        robot1.setCode("err");
        robot1.setState(0);

        Robot robot2 = new Robot();
        robot2.setId("002");
        robot2.setName("v3");
        robot2.setPoint(Arrays.asList(new String[]{"e", "c"}));
        robot2.setCode("ok");
        robot2.setState(1);

        List<Robot> list = new ArrayList<>();
        list.add(robot1);
        list.add(robot2);

        String jsonStr = JSON.toJSONString(list);
        System.out.println(jsonStr);
    }
_________________________
 [{"code":"err","id":"001","name":"v7","point":["a","b"],"state":0},{"code":"ok","id":"002","name":"v3","point":["e","c"],"state":1}]

Map-->json

 public static void mapToJson() {
        Robot robot = new Robot();
        robot.setId("001");
        robot.setName("v7");
        robot.setPoint(Arrays.asList(new String[]{"a", "b"}));
        robot.setCode("err");
        robot.setState(0);

        Map<String, Robot> map = new HashMap<>();
        map.put("rb1", robot);
        // {"rb1":{"code":"err","id":"001","name":"v7","point":["a","b"],"state":0}}
        String jsonStr = JSON.toJSONString(map);
        System.out.println(jsonStr);
}

json --> object

 public static void json2Object() {
        String path = System.getProperty("user.dir") + "/config/rb.json";
        File file = new File(path);
        String jsonStr = null;
        try {
            jsonStr = FileUtil.readAsString(file);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        Robot robot = JSONObject.parseObject(jsonStr, Robot.class);
        System.out.println(robot.toString());
    }

json --> List(Object)

[
  {
    "code": "err",
    "id": "002",
    "name": "v1",
    "point": [
      "a",
      "b"
    ],
    "state": 0
  },
  {
    "code": "err",
    "id": "002",
    "name": "v2",
    "point": [
      "a",
      "b"
    ],
    "state": 0
  }
]
  public static void json2ObjectList() {
        String path = System.getProperty("user.dir") + "/config/rbs.json";
        File file = new File(path);
        String jsonStr = null;
        try {
            jsonStr = FileUtil.readAsString(file);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        List<Robot> list = JSON.parseArray(jsonStr, Robot.class);
        System.out.println(list);
}

json --> Map

{
  "rb1": {
    "code": "err",
    "id": "002",
    "name": "v1",
    "point": [
      "a",
      "b"
    ],
    "state": 0
  },
  "rb2": {
    "code": "err",
    "id": "002",
    "name": "v2",
    "point": [
      "a",
      "b"
    ],
    "state": 0
  }
}
 public static void json2Map() {
        String path = System.getProperty("user.dir") + "/config/rbMap.json";
        File file = new File(path);
        String jsonStr = null;
        try {
            jsonStr = FileUtil.readAsString(file);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Map<String, Robot> map = JSON.parseObject(jsonStr, new TypeReference<Map<String, Robot>>(){});
        // rb1->Robot(id=002, name=v1, state=0, code=err, point=[a, b])
        // rb2->Robot(id=002, name=v2, state=0, code=err, point=[a, b])
        map.forEach((id, value) -> {
            System.out.println(id + "->" + value);
        });
    }

posted @ 2023-01-16 01:13  shmilyt  阅读(1714)  评论(0编辑  收藏  举报