springboot-读取配置文件属性

本文详细介绍了如何在Spring Boot应用中使用YAML配置文件进行属性设置,包括自定义属性、随机值生成及属性之间的引用。同时展示了两种读取配置的方式:通过@Value和@ConfigurationProperties注解。

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

一.配置属性写在系统自带的yml配置文件里面

1.yml配置文件自定义属性

#自定义属性
book:
  name: name
  author: author
  #随机字符串
  value: ${random.value}
  #随机int值
  intValue: ${random.int}
  #随机long值
  longValue: ${random.long}
  #随机uuid
  uuid: ${random.uuid}
  #1000以内随机数
  randomNumber: ${random.int(1000)}
  #10-100以内随机数
  randomNum: ${random.int[10,100]}
  #自定义属性之间的引用
  title: 书名是:${book.name}

1_1.读取方式_@value注解

    @Value("${book.name}")
    private String bookName;

    @Value("${book.author}")
    private String bookAuthor;

1_2.读取方式_@ConfigurationProperties注解

@ConfigurationProperties(prefix = "book")
public class BookConfigBean {
    private String name;
    private String author;
    //随机字符串
    private String value;
    //随机int值
    private int intValue;
    //随机long值
    private long longValue;
    //随机uuid
    private String uuid;
    //1000以内随机数
    private int randomNumber;
    //10-100以内随机数
    private int randomNum;
    //自定义属性之间的引用
    private String title;
}

二.自定义配置文件test.properties

2.test.properties文件内容

#注意编码格式 中文建议用unicode
com.book.name = \u4e66\u540d
com.book.author = \u4f5c\u8005

2_1.读取方式

@Component
@PropertySource(value = "classpath:test.properties")
@ConfigurationProperties(prefix = "com.book")
public class ConfigBean {
    private String name;
    private String author;

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值