SpringBoot之yml文件

读取yml的单一变量

在属性名上使用

在指定的属性上使用org.springframework.beans.factory.annotation包下的@Value注解,在注解中使用 “${变量名}” 的方式定位到yml数据。

yml获取变量

在这里插入图片描述

读取yml文件的引用类型数据

既然是引用类型,那么就需要创建一个类来映射这些信息

  • 先看看yml里面的数据
human:
  age: 10
  name: asher
  height: 180cm
  • 来看看对应的类
@Data
@Component(value = "human")
@ConfigurationProperties(prefix = "human")
public class Human {
    private int age;
    private String name;
    private String height;
}


/**
说明:
1. 由于需要让spring来帮助我们自动装配,所以需要@Component注解来声明这是一个Spring Bean
2. Spring装配Bean需要有Getter和Setter方法,这里使用lombok提供的@Data注解
3. 要在类上添加@ConfigurationProperties(prefix = "human")注解来定位到yml文件中的引用类型对象
4. 创建的类的属性需要和yml中的key名称相同,如果不同,则读取为null,解决办法是在指定的属性上使用org.springframework.beans.factory.annotation包下的@Value注解,在注解中定位到yml数据。例如   
    @Value("${human.name}")
    private String nae;  //将上面的name改成nae

*/

引用类型嵌套引用类型

  • 先看看yml里面的数据
human:
  age: 10
  name: asher
  height: 180cm
  children:
    baby1: asher-baby1
    baby2: asher-baby2
  • 来看看对应的类
@Data
@Component(value = "human")
@ConfigurationProperties(prefix = "human")
public class Human {
    private int age;

    private String name;
    private String height;
    private Children children;
}
@Data
@Component
@ConfigurationProperties(prefix = "human.children")
class Children{
    private String baby1;
    private String baby2;
}

主程序:

@SpringBootApplication
public class Main {
    public static void main(String[] args) {
        ConfigurableApplicationContext run = SpringApplication.run(Main.class, args);
        Human human = (Human)run.getBean("human");
        System.out.println(human);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值