这篇文章主要介绍了SpringBoot中如何解决读取properties文件读取问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
如何解决读取properties文件读取问题
问题描述
今天在springboot项目架构中,测试读取properties配置文件出现了两个问题:
- 路径设置
- 中文乱码
路径设置
解决思路是使用org.springframework.core.io下的ClassPathResource类获取流对象,然后使用properties进行读取
中文乱码
将从ClassPathResource中获取的流对象转换为BufferReader对象
public static void main(String[] args) throws IOException {
Properties properties = new Properties();
ClassPathResource classPathResource = new ClassPathResource("ProducerQuickStart.properties");
InputStream inputStream = classPathResource.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
properties.load(bufferedReader);
Set<Object> keySets = properties.keySet();
Iterator<Object> iterator = keySets.iterator();
while (iterator.hasNext()){
Object obj = iterator.next();
System.out.println("键:"+obj+" 值:"+properties.get(obj));
}
}
读取指定properties文件
设置配置属性类型
/**
* 自定义配置属性类
* @author ZH_FTP
*
*/
@Component
//springboot 管理
@ConfigurationProperties(prefix = "validity")
//键值前缀
@PropertySource(value = {"classpath:/config/baseproperties.properties"}, encoding = "utf-8")
// 配置文件路径 解码方式
public class BaseProperties {
private static final int INT_ZERO = 0;
@Value("${validity.of.captcha}")
private Integer validityOfCaptcha;//验证码有效时间
public Integer getValidityOfCaptcha() {
return validityOfCaptcha;
}
public void setValidityOfCaptcha(Integer validityOfCaptcha) {
this.validityOfCaptcha = validityOfCaptcha;
}
}
配置文件
在工程 /src/main/resources/config/baseproperties.properties 文件类型 配置信息 方便配置类读取
validity.of.captcha=120
读取配置文件就完成了,可以通过springboot 自动注入使用了
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程学习网。
沃梦达教程
本文标题为:SpringBoot中如何解决读取properties文件读取问题


基础教程推荐
猜你喜欢
- java 解决Eclipse挂掉问题的方法 2024-01-10
- springboot中request和response的加解密实现代码 2022-12-08
- JSP servlet实现文件上传下载和删除 2023-07-30
- 详解http请求中的Content-Type 2023-07-31
- 用javascript制作qq注册动态页面 2023-12-16
- SpringBoot 2.5.5整合轻量级的分布式日志标记追踪神器TLog的详细过程 2023-06-17
- jsp hibernate的分页代码第3/3页 2024-01-11
- 关于@MapperScan包扫描的坑及解决 2023-04-16
- Spring MVC数据绑定方式 2023-06-30
- SpringBoot嵌入式Web容器原理与使用介绍 2023-06-17