Java中解析yml或yaml配置文件

本文介绍了在Spring Boot中读取YAML配置文件的三种方式:@Value注解、Environment对象和自定义对象,并详细展示了每种方式的实现步骤和运行结果。此外,还提供了当使用自定义对象封装数据时遇到警告的解决方案,即添加spring-boot-configuration-processor依赖。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


编写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);
    }
}

运行结果:
@Value注解实现运行结果


方式二:封装全部数据到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);
    }
}

运行结果:
封装全部数据到Environment对象运行结果


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

可实现数组封装

实现步骤:
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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值