SpringBoot读取yml中的配置,并分离配置文件

本文介绍如何在SpringBoot项目中通过YAML配置文件实现配置信息的分离与加载,包括使用@Component和@ConfigurationProperties注解来读取配置文件,并提供了一个简单的测试案例。

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

前言

在项目中经常遇到需要读取配置文件中的配置信息,这些配置信息之所以不写在代码中是因为实际项目发布或者部署之后会进行更改,而如果写在代码中编译之后没有办法进行修改。
之前使用的是properties进行的配置和读取的。
而在SpringBoot中我们采用yml的配置时也需要读取配置文件中的信息。
同时因为这样会导致配置文件增多,所以我们需要分离配置文件。

github:https://github.com/LinkinStars/springBootTemplate

分离配置文件

在application.yml使用include加载不同的配置文件,如下是加载application-config.yml配置文件

spring:
  # 选择加载不同环境的配置文件
  profiles:
    active: dev
    include: config

在application-config.yml配置文件中加入测试参数
demo:
  id: 1
  val: 123

读取配置文件

使用@Component和@ConfigurationProperties注解实现,如下

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
* 读取配置文件中的信息
* @author LinkinStar
*/
@Component
@ConfigurationProperties(prefix = "demo")
public class DemoConfig {
private int id;
private String val;

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getVal() {
    return val;
}

public void setVal(String val) {
    this.val = val;
}
}

 

 

如何使用

/**
* Demo读取配置测试
* @author LinkinStar
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoConfigTest {

@Autowired
private DemoConfig demoConfig;

@Test
public void getDemoConfig(){
    System.out.println(demoConfig.getId());
    System.out.println(demoConfig.getVal());
}
}

 

 

总结

1、这些配置主要用于存放那些容易被修改的配置。
2、@ConfigurationProperties和@Value的区别是:前一个作用于对象也就是批量的注入配置信息,而后者是单个指定。
3、分离配置文件同时可以用于分离别的配置信息。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值