Java中解析yml或yaml配置文件


编写yaml文件

# yml文件自定义配置
information:
  name: 小明
  age: 16
  tel: 88888888888
  address: 北京市
  subject:
    - 数学
    - 英语
    - 语文
    - 物理
    - 化学

方式一:@Value注解(只注入单个元素)

实现步骤:

@SpringBootTest
public class ResourcesTest {
          
   

    @Value("${information.name}")
    private String name;
    @Value("${information.age}")
    private Integer age;
    @Value("${information.tel}")
    private String tel;
    @Value("${information.address}")
    private String address;
    @Value("${information.subject[0]}")//只能注入单个属性
    private String subject;

    @Test
    public void testValue(){
          
   
        System.out.println("姓名:"+name);
        System.out.println("年龄:"+age);
        System.out.println("电话:"+tel);
        System.out.println("住址:"+address);
        System.out.println("学科:"+subject);
    }
}

运行结果:


方式二:封装全部数据到Environment对象

实现步骤:

@SpringBootTest
public class ResourcesTest {
          
   

    @Autowired
    private Environment environment; //容器中已经加载了这个对象,并且封装了所有的属性

    @Test
    public void testEnvironment(){
          
   
        String name = environment.getProperty("information.name");
        String age = environment.getProperty("information.age");
        String subject = environment.getProperty("information.subject[0]");
        System.out.println("姓名:"+name);
        System.out.println("年龄:"+age);
        System.out.println("学科:"+subject);
    }
}

运行结果:


方式三:自定义对象封装指定数据【常用】

可实现数组封装

实现步骤: 1、定义实体类用于封装数据

@Component //将对象添加Spring容器中,在类上添加@Component注解
@ConfigurationProperties(prefix = "information") //在类上添加@ConfigurationProperties(prefix="指定前缀")
@Data
public class Information {
          
   

    private String name;
    private Integer age;
    private String tel;
    private String address;
    private String[] subject;
}

2、实现

@SpringBootTest
public class ResourcesTest {
          
   

    @Autowired
    private Information information;

    @Test
    public void testSelfdefining(){
          
   
        System.out.println(information);
    }
}

运行结果:


拓展:自定义对象封装数据警告解决方案

在自定义对象使用 @ConfigurationProperties 注解会出现以下警告

Spring Boot Configuration Annotation Processor not configured

只需要在pom.xml添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>
经验分享 程序员 微信小程序 职场和发展