Springboot获取yml的属性

文章介绍了SpringBoot中yml配置文件的优先级规则,以及三种不同的属性获取方式:通过@Value注解、使用Environment对象和创建配置属性的实体类。详细展示了如何读取多层级数据和数组,并提供了示例代码。

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

yml配置文件使用


启动配置文件优先级:properties高于yml高于yaml

获取yml及yaml的属性方式

yml或者yaml里的属性

lesson: SpringBoot

server:
  port: 81

enterprise:
  name: testName
  age: 16
  tel: 123456789
  subject: #这个是数组 数组用-号空格书写
    - Java
    - 前端
    - 大数据

方式一(加Value注解)

//数据无层级获取方式
@Value("${lesson}")
private String lesson;

//多层级获取方式在层级后面用 . 来连接
@Value("${server.port}")
private Integer port;

//读取配置文件里面多层级数组的数据
@Value("${enterprise.subject[0]}")//通过索引读取数组里的第一个数据
private String subject_00;

方式二(把yml或者yaml文件编程Bean交给Springboot管理)

//自动装配Environment环境对象,他会自动获取yml或者yaml的全部数据
@Autowired
private Environment environment;

//通过environment.getProperty加key值获取
@RequestMapping("/helloOne")
public String helloOne(){
    
    String lesson1 = environment.getProperty("lesson");
    String property = environment.getProperty("enterprise.age");
    
}

方式三(获取yml或者yaml的第一级属性名称,通过实体类封装属性)

//先把这个实体类变成Bean交个Springboot管理,这样springboot才能把这个实体类跟配置文件匹配
@Component
//这里的prefix(key值)对应的是yml或者yaml中第一级属性名(要哪个属性就写哪个属性名)
@ConfigurationProperties(prefix = "enterprise") 
//这个注解包含get、set、equals、hashCode、canEqual、toString、无参构造方法
@Data
public class Enterprise {
    private String name;
    private Integer age;
    private String tel;
    private String[] subject;
}

方式三读取数据语法

//获取到定义的实体类
@Autowired
private Enterprise enterprise;

@RequestMapping("/helloOne")
public String helloOne(){
    Integer age = enterprise.getAge();
    String name = enterprise.getName();
    String tel = enterprise.getTel();
    String[] subject = enterprise.getSubject();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值