Springboot加载自定义yml文件配置的方法

本文讲解到的知识点是基于Springboot 2.1.5.RELEASE的版本。

首先先在resources目录下创建一个测试用的yml配置文件,内容如下:

PS:注意yml文件中key: value的冒号后面是有一个空格的

system:
  user:
    name: zjhuang
    password: 123456
    age: 25

一. @PropertySource + @Value

  • 配置参数类代码
  1. @PropertySource: 为了告知springboot加载自定义的yml配置文件,springboot默认会自动加载application.yml文件,如果参数信息直接写在这个文件里,则不需要显式加载。
  2. @Value: 指定目标属性在yml’文件中的全限定名。
  3. @Component: 作用是将当前类实例化到spring容器中,相当于xml配置文件中的<bean id="" class=""/>
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource(value = "classpath:test.yml")
public class YamlProperties {
   

    @Value("${system.user.name}")
    private String name;
    @Value("${system.user.password}")
    private String password;
    @Value("${system.user.age}")
    private int age;

    // Setter...
    // Getter...
    // toStr
  • 12
    点赞
  • 49
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值