首页 > 其他分享 >springboot之json/yml配置文件的读取

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

时间:2023-01-16 01:22:18浏览次数:50  
标签:springboot 配置文件 private String json import config name

配置文件读取

项目根目录的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;
        }
    }
}
图片名称 图片名称

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转指定对象

还是以下面的device.json文件为例:

构建pojo类Robot, 其中故意增加一个没有的字段code:

@Data
public class Robot {
    private String id;
    private String name;
    private int state;
    private String code;

    private List<String> point;
}

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

json文件转为指定的对象列表

如下为goods.json文件, 想转为List类型

[
  {
    "id": 1,
    "name": "robot1",
    "state": 0,
    "point": [
      1,
      2
    ]
  },
  {
    "id": 2,
    "name": "robot2",
    "state": 1,
    "point": [
      3,
      4
    ]
  }
]

借助JSON.parseArray

 public void getObjectArray() {
        String path = System.getProperty("user.dir") + File.separator + "config" + File.separator + "goods.json";
        File file = new File(path);
        try {
            String json = FileUtils.readFileToString(file);
            List<Robot> list = JSON.parseArray(json,Robot.class);
            System.out.println(list.get(0));
            System.out.println(list.get(1));


        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
______________________________________
Robot(id=1, name=robot1, state=0, code=null, point=[1, 2])
Robot(id=2, name=robot2, state=1, code=null, point=[3, 4])

标签:springboot,配置文件,private,String,json,import,config,name
From: https://www.cnblogs.com/shmilyt/p/17054555.html

相关文章

  • JSON
    1.概念:JavaScriptObjectNotation  JavaScript对象表示法   varp={"name":"zhangsan","age":23,"sex":"男"}    *json现在多用于储存和交换文本信息的语法......
  • springboot集成nacos 配置中心
    nacos本机需要安装好,未安装时,参考创建一个springbootmyapi项目,使用maven进行依赖包管理,创建两个模块nacosconfig(配置中心)、nacosregister,(注册中心),本方主......
  • 230115_50_SpringBoot入门
    如果类中属性比较多,通过@value赋值比较麻烦。可以通过yaml配置文件给实例赋值。新建Person类,通过@ConfigurationProperties注解可以实现配置文件注入,其中prefix可以指......
  • springboot url中获取所有RequestMapping的URL路径列表集
    springboot项目在做URL权限控制的时候需要获取全部的URL,一个一个去controller中找费时费力,有的权限点的命名和URL有一定的对应关系。如果能用程序获得全部URL,将会省去很......
  • Spring Boot---(11)SpringBoot使用Junit单元测试
    摘要:本文详细的记录了SpringBoot如何结合Junit写测试用例,如何执行,打包执行,忽略执行等操作,SpringBoot内置了Junit测试组件,使用很方便,不用再单独引入其他测试组件。 演示环境......
  • SpringBoot完成SSM整合之SpringBoot整合junit
    SpringBoot​​......
  • 48、商品服务---品牌管理---JSON格式化工具
    https://www.bejson.com/可以直接将我们的json数据生成对应的Java实体类,不用我们手写了......
  • springboot2.3.x版本发生异常时,响应的message和exception为空问题
    原因:因为boot2.3.x版本可能考虑信息安全问题,把以下两个值默认为server:error:include-message:neverinclude-exception:false发生异常是返回{"ti......
  • Net 6 控制台配置文件读取
    原文网址:https://blog.csdn.net/shuikanshui/article/details/122809945一、使用App.Config作为配置文件1、项目增加应用程序配置文件App.config2、文件设置为“如果较......
  • Shiro+SpringBoot+Mybatis+Redis实现权限系统
     这个项目涉及到的技术:SpringBoot,Thymeleaf,MyBaits,Redis,Shiro,JavaMail,EasyUI,Excel导入、导出 下面展示一下界面: 主页:  用户列表:  角色权限授予: 资源列表:  用户角......