springboot中.properties和.yml文件的读取方式和优先级

两种配置文件的格式

在springboot框架中,resource文件夹里可以存放配置的文件有两种:properties和yml。

1、application.properties的用法:扁平的k/v格式。

server.port=8801

eureka.client.register-with-eureka=false

eureka.client.fetch-registry=false

eureka.client.serviceUrl.defaultZone=http\://localhost\:${server.port}/eureka/

2、application.yml的用法:树型结构。

server:

    port: 8801

eureka:

    client:

      registerWithEureka: false

      fetchRegistry: false

      serviceUrl:

      defaultZone: http://localhost:8801/eureka/

两种前者是,而后者是yml的,建议使用后者,因为它的可读性更强,如果现有是properties,也可以转换成yml格式,我们把properies里按.去拆分即可。

两种配置文件的读取

例application.properties:

test.name=guoqing
test.birth=1001
test.mj=980

application.yml:

test:
   mj: 960

使用@Value注解读取

1\

    @Value("${demo.name}")
    private String name;
 
    @Value("${demo.age}")
    private String age;

    @Value("${test.mj}")
    private String mj;

    @RequestMapping("/getProperties")
    public String getProperties(){
        log.info("读取properties文件结果:name->{};birth->{};mj->{}",name,birth,mj);
        return "读取properties文件结果name->"+name+";birth->"+birth;
    }

运行结果:

2\

也可以单独放在一个类

@Component
public class China {
    @Value("${test.name}")
    private String name;

    @Value("${test.birth}")
    private String birth;

    @Value("${test.mj}")
    private String mj;

    public String getName() {
        return name;
    }

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

    public String getBirth() {
        return birth;
    }

    public void setBirth(String birth) {
        this.birth = birth;
    }

    public String getMj() {
        return mj;
    }

    public void setMj(String mj) {
        this.mj = mj;
    }
}

调用

public class TestController {

    @Autowired
    private China china;

    @RequestMapping("/getProperties")
    public String getProperties(){
        log.info("读取结果:name->{};birth->{};mj->{}",
                           china.getName(),china.getBirth(),china.getMj());
        return "读取properties文件结果name->"+china.getName()+";birth->"+china.getBirth();
    }
}

两种配置文件的优先级

优先读取properties文件,如果properties文件中没有再去读yml文件。

  • application.properties(或者application.yml)中包含系统属性、环境变量、命令参数这类信息。
  • application.yml代码量 更少,层次更加分明,结构更加清晰,推荐使用application.yml
  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值