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