SpringBoot中如何解決讀取properties文件讀取問題
如何解決讀取properties文件讀取問題
問題描述
今天在springboot項(xiàng)目架構(gòu)中,測試讀取properties配置文件出現(xiàn)了兩個(gè)問題:
- 路徑設(shè)置
- 中文亂碼
路徑設(shè)置
解決思路是使用org.springframework.core.io下的ClassPathResource類獲取流對象,然后使用properties進(jìn)行讀取
中文亂碼
將從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;//驗(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
讀取配置文件就完成了,可以通過springboot 自動注入使用了
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Spring很常用的@Conditional注解的使用場景和源碼解析
今天要分享的是Spring的注解@Conditional,@Conditional是一個(gè)條件注解,它的作用是判斷Bean是否滿足條件,本文詳細(xì)介紹了@Conditional注解的使用場景和源碼,需要的朋友可以參考一下2023-04-04
JDBC以反射機(jī)制加載類注冊驅(qū)動連接MySQL
這篇文章介紹了JDBC以反射機(jī)制加載類注冊驅(qū)動連接MySQL的方法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-01-01
Java中的ConcurrentLinkedQueue松散隊(duì)列解析
這篇文章主要介紹了Java中的ConcurrentLinkedQueue松散隊(duì)列解析,鏈表是松散的,鏈表節(jié)點(diǎn)并不都是有效的,允許存在無效節(jié)點(diǎn)val=null,但是只有最后一個(gè)節(jié)點(diǎn)才能next=null,需要的朋友可以參考下2023-12-12

