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)文章
使用FeignClient設(shè)置動態(tài)Url
這篇文章主要介紹了使用FeignClient設(shè)置動態(tài)Url方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06
Java Web Filter 過濾器學(xué)習(xí)教程(推薦)
Filter也稱之為過濾器,它是Servlet技術(shù)中最激動人心的技術(shù).這篇文章主要介紹了Java Web Filter 過濾器學(xué)習(xí)教程的相關(guān)資料,需要的朋友可以參考下2016-05-05
springSecurity之AuthenticationProvider用法解析
這篇文章主要介紹了springSecurity之AuthenticationProvider用法解析,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-03-03
MyBatis-Plus中最簡單的查詢操作教程(Lambda)
這篇文章主要給大家介紹了關(guān)于MyBatis-Plus中最簡單的查詢操作的相關(guān)資料,文中通過實例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2022-03-03

