SpringBoot中如何解決讀取properties文件讀取問題
如何解決讀取properties文件讀取問題
問題描述
今天在springboot項目架構(gòu)中,測試讀取properties配置文件出現(xiàn)了兩個問題:
- 路徑設(shè)置
- 中文亂碼
路徑設(shè)置
解決思路是使用org.springframework.core.io下的ClassPathResource類獲取流對象,然后使用properties進行讀取
中文亂碼
將從ClassPathResource中獲取的流對象轉(zhuǎn)換為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文件
設(shè)置配置屬性類型
/** ?* 自定義配置屬性類 ?* @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 自動注入使用了
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Spring很常用的@Conditional注解的使用場景和源碼解析
今天要分享的是Spring的注解@Conditional,@Conditional是一個條件注解,它的作用是判斷Bean是否滿足條件,本文詳細介紹了@Conditional注解的使用場景和源碼,需要的朋友可以參考一下2023-04-04Java中的ConcurrentLinkedQueue松散隊列解析
這篇文章主要介紹了Java中的ConcurrentLinkedQueue松散隊列解析,鏈表是松散的,鏈表節(jié)點并不都是有效的,允許存在無效節(jié)點val=null,但是只有最后一個節(jié)點才能next=null,需要的朋友可以參考下2023-12-12