这篇文章主要介绍了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文件读取问题


基础教程推荐
猜你喜欢
- 工厂方法在Spring框架中的运用 2023-06-23
- 一文了解Java 线程池的正确使用姿势 2023-06-17
- Java File类的概述及常用方法使用详解 2023-05-18
- 用java实现扫雷游戏 2022-12-06
- Java使用EasyExcel进行单元格合并的问题详解 2023-01-18
- Java去掉小数点后面无效0的方案与建议 2023-02-18
- SpringBoot配置文件中密码属性加密的实现 2023-03-11
- JVM分析之类加载机制详解 2023-04-06
- Project Reactor源码解析publishOn使用示例 2023-04-12
- 全局记录Feign的请求和响应日志方式 2023-01-09