SpringBoot配置文件读取


前言

在SpringBoot中有默认给的application.properties配置文件,还有一些自定义的配置文件,本文将介绍这些配置文件的读取方式。

一、读取默认配置文件

application.properties文件内容:

test = 这是一个曲折的测试

使用@Value("${}")注解来读取文件内容:

public class Test {
    @Value("${test}")
    private String test;
}

二、读取自定义配置文件

2.1@PropertiesSource+@Value注解读取文件内容

自定义配置文件名:student-info.properties,内容为:

no = s10001
name = 张三
age = 18
male =

读取文件内容,config/student-info.properties是文件的路径

@PropertySource(value = "classpath:config/student-info.properties")
public class Student {

    @Value("${no}")
    private String no;
    @Value("${name}")
    private String name;
    @Value("${age}")
    private Integer age;
    @Value("${male}")
    private String male;
}

2.2@PropertiesSource+@ConfigurationProperties注解读取文件内容

自定义文件名:phone.properties,内容为:

phone.id = p0001
phone.category = iphone
phone.price = 6400

读取文件内容,config/phone.properties为文件路径

@PropertySource("classpath:config/phone.properties")
@ConfigurationProperties(prefix = "phone")
public class Phone {
    private String id;
    private String category;
    private float price;
}

这里@ConfigurationProperties有点不同,需要使用prefix = “phone”,即配置文件内容的前缀,这边id、category、price成员变量上就不需要标记@Value注解,也可以让phone.id的值自动赋给id,其他成员也是如此。

三、在读取文件时出现中文乱码问题

出现乱码主要是因为文件的编码格式和我们读取的格式不匹配,只要将配置文件的编码格式进行修改即可
打开File–>Setting–>Editor–>File Encoding中设置文件的编码格式在这里插入图片描述在这里插入图片描述
将文件的编码格式修改成UTF-8即可


总结

SpringBoot配置文件的读取在日常开发中是非常重要的一环,本文简单的介绍了一些配置文件的读取方式和中文乱码问题的解决方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值