SpringBoot中如何解决读取properties文件读取问题

这篇文章主要介绍了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 keySets = properties.keySet();         Iterator 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 自动注入使用了

以上为个人经验,希望能给大家一个参考,也希望大家多多支持0133技术站。 

以上就是SpringBoot中如何解决读取properties文件读取问题的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » Java