SpringBoot中如何解決讀取properties文件讀取問(wèn)題
如何解決讀取properties文件讀取問(wèn)題
問(wèn)題描述
今天在springboot項(xiàng)目架構(gòu)中,測(cè)試讀取properties配置文件出現(xiàn)了兩個(gè)問(wèn)題:
- 路徑設(shè)置
- 中文亂碼
路徑設(shè)置
解決思路是使用org.springframework.core.io下的ClassPathResource類獲取流對(duì)象,然后使用properties進(jìn)行讀取
中文亂碼
將從ClassPathResource中獲取的流對(duì)象轉(zhuǎn)換為BufferReader對(duì)象
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;//驗(yàn)證碼有效時(shí)間 ?? ?public Integer getValidityOfCaptcha() { ?? ??? ?return validityOfCaptcha; ?? ?} ?? ?public void setValidityOfCaptcha(Integer validityOfCaptcha) { ?? ??? ?this.validityOfCaptcha = validityOfCaptcha; ?? ?} }
配置文件
在工程 /src/main/resources/config/baseproperties.properties 文件類型 配置信息 方便配置類讀取
validity.of.captcha=120
讀取配置文件就完成了,可以通過(guò)springboot 自動(dòng)注入使用了
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Spring很常用的@Conditional注解的使用場(chǎng)景和源碼解析
今天要分享的是Spring的注解@Conditional,@Conditional是一個(gè)條件注解,它的作用是判斷Bean是否滿足條件,本文詳細(xì)介紹了@Conditional注解的使用場(chǎng)景和源碼,需要的朋友可以參考一下2023-04-04Spring EL表示式的運(yùn)用@Value說(shuō)明
這篇文章主要介紹了Spring EL表示式的運(yùn)用@Value說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-04-04JDBC以反射機(jī)制加載類注冊(cè)驅(qū)動(dòng)連接MySQL
這篇文章介紹了JDBC以反射機(jī)制加載類注冊(cè)驅(qū)動(dòng)連接MySQL的方法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-01-01Java中的ConcurrentLinkedQueue松散隊(duì)列解析
這篇文章主要介紹了Java中的ConcurrentLinkedQueue松散隊(duì)列解析,鏈表是松散的,鏈表節(jié)點(diǎn)并不都是有效的,允許存在無(wú)效節(jié)點(diǎn)val=null,但是只有最后一個(gè)節(jié)點(diǎn)才能next=null,需要的朋友可以參考下2023-12-12