这篇文章主要介绍了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文件读取问题
基础教程推荐
猜你喜欢
- JSP 动态树的实现 2023-12-17
- 深入理解约瑟夫环的数学优化方法 2024-03-07
- 运用El表达式截取字符串/获取list的长度实例 2023-08-01
- 是否适合从javabean类更新数据库? 2023-11-04
- Java编写实现窗体程序显示日历 2023-01-02
- Java+mysql实现学籍管理系统 2023-03-16
- springboot下使用shiro自定义filter的个人经验分享 2024-02-27
- JavaWeb 实现验证码功能(demo) 2024-04-14
- 使用Java和WebSocket实现网页聊天室实例代码 2024-02-25
- Java中EnvironmentAware 接口的作用 2023-01-23
