SpringBoot读取配置文件的几种方式

日积月累,水滴石穿 😄

前言

SpringBoot 中呢,我们经常要读取配置文件的值,那读取配置文件的值有哪几种方式呢?跟着笔者一起来看看吧!

一、使用@Value注解

先准备一下两个配置文件,名称为:application.propertiesapplication.yml

  • properties
userproperties.name=gongj===properties
userproperties.age=11===properties
userproperties.sex=12===properties
userproperties.email=3333@163.com===properties 
  • yml
useryml:
  name: gongjie
  age: 23
  sex: 1
  email: 111@163.com 
  • 测试
 @Value("${userproperties.name}")
    private String name;
    @Value("${userproperties.age}")
    private String age;
    @Value("${userproperties.sex}")
    private String sex;
    @Value("${userproperties.email}")
    private String email;

    @Value("${useryml.name}")
    private String nameyml;
    @Value("${useryml.age}")
    private String ageyml;
    @Value("${useryml.sex}")
    private String sexyml;
    @Value("${useryml.email}")
    private String emailyml;

    @Test
    public void testValue(){
   
    
        System.out.println("name=" + name + ",age=" + age + ",sex=" 
        + sex + ",email" + email);
        
       System.out.println("nameyml=" + nameyml + ",ageyml=" + ageyml 
       + ",sexyml=" + sexyml + ",emailyml" + emailyml);
    } 

image.png

二、使用@ConfigurationProperties注解

  • properties
@Component
@ConfigurationProperties(prefix = "userproperties")
public class ReadPropertiesValue {
   
    private String name;
    private String age;
    private String email;
    private String sex;

    @Override
    public String toString() {
   
        return "ReadPropertiesValue{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", email='" + email + '\'' +
                ", sex=" + sex +
                '}';
    }

    public void setName(String name) {
   
        this.name = name;
    }

    public void setAge(String age) {
   
        this.age = age;
    }

    public void setEmail(String email) {
   
        this.email = email;
    }

    public void setSex
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

图灵课堂诸葛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值